当前位置: 首页 > article >正文

【vue3】 defineExpose 的使用

以下是 Vue3 中defineExpose的使用方法:

基本概念

defineExpose是 Vue3 中的一个工具函数,是仅能在<script setup>中使用的函数,用于显式暴露组件内部的属性或方法给父组件使用2。在 Vue3 的<script setup>中,组件的状态和方法默认是私有的,父组件即使通过ref引用子组件实例,也无法访问其中的内容,使用defineExpose可以打破这一限制.

基本用法

defineExpose的基本语法是defineExpose(exposedObject)。其中,exposedObject是一个对象,用于定义要暴露的属性或方法

示例

  • 暴露函数
<!-- 子组件ChildComponent.vue -->
<template>
    <h2>子组件</h2>
</template>
<script setup>
import { ref } from 'vue';
const message = ref('Hello from Child Component');
// 定义一个供父组件调用的函数
function childMethod() {
    console.log('子组件方法被调用!');
}
// 使用defineExpose暴露message和childMethod
defineExpose({
    message,
    childMethod
});
</script>
<!-- 父组件 -->
<template>
    <h1>父组件</h1>
    <ChildComponent ref="childRef" />
    <button @click="callChildMethod">调用子组件方法</button>
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const childRef = ref(null);
function callChildMethod() {
    // 通过ref调用子组件暴露的方法
    console.log(childRef.value.message);
    childRef.value.childMethod();
}
</script>
  • 暴露数据
<!-- 子组件 -->
<script setup>
import { ref } from 'vue';
// 子组件内部的状态和方法
const count = ref(0);
// 通过defineExpose暴露给父组件
defineExpose({
    count
});
</script>
<template>
    <p>计数器子组件:{{ count }}</p>
</template>
<!-- 父组件 -->
<script setup>
import { ref } from 'vue';
import Counter from './Counter.vue';
// 通过ref获取子组件实例
const counterRef = ref(null);
function callChildMethod() {
    console.log('子组件计数值:', counterRef.value.count);
}
</script>
<template>
    <Counter ref="counterRef" />
    <button @click="callChildMethod">获取子组件计数值</button>
</template>

注意事项

  • defineExpose应该放在<script setup>的末尾,因为任何在它之后声明的变量或函数都不会被自动包含在暴露的对象中4。
  • 当组件中包含<script setup>和普通<script>时,<script>中定义的数据和方法不会被暴露

<template>
  <!-- 组件模板 -->
</template>

<script setup>
  import { ref, onMounted } from 'vue';

  // 这些内容会被 expose 出去
  const count = ref(0);
  function increment() {
    count.value++;
  }

  // 定义暴露出去的 API
  defineExpose({
    count,
    increment
  });

  // 这个函数不会被 expose 出去,因为它在 defineExpose 调用之后定义
  function decrement() {
    count.value--;
  }
</script>

http://www.kler.cn/a/505577.html

相关文章:

  • IIO(Industrial I/O)驱动介绍
  • 使用分割 Mask 和 K-means 聚类获取天空的颜色
  • 爬虫后的数据处理与使用(使用篇--实现分类预测)
  • css 三角构建
  • MCU中实时时钟(RTC)和普通定时器有什么区别
  • 深入Android架构(从线程到AIDL)_32 JNI架构原理_Java与C的对接05
  • C -- 大端对齐 小端对齐 的人性化解释
  • HTTP 缓存机制详解
  • matlab专栏-M文件
  • 学生资助在线管理软件开发微信小程序ssm+论文源码调试讲解
  • 《AI发展的三个关键视角:基础设施、开源趋势与社会影响》
  • SpringBoot + Websocket实现系统用户消息通知
  • Web后端开发
  • 《零基础Go语言算法实战》【题目 4-6】随机选择单链表的一个节点并返回
  • 《零基础Go语言算法实战》【题目 2-20】通过泛型比较大小
  • 设计模式--命令模式【行为型模式】
  • 【JavaWeb01】JavaWeb开发基础:HTML的深度解析与应用
  • 【计算机网络】lab8 DNS协议
  • Postman下载与使用,新手详细
  • android T 建立文件夹及文件的记录