t.csdn.cn/hWwZd 文章内容引用此链接
基本使用
官方文档指出默认情况下使用 <script setup> 的组件是默认关闭的,也就是说通过模板 ref 或者 $parent 链获取到的组件的实例,并不会暴露任何在 <script setup> 中声明的绑定(变量,函数)。
为了在 <script setup> 组件中明确要暴露出去的属性,那么就需要使用 defineExpose 这个宏命令。
// 父组件
<template>
<ChildRen ref="infoRef" />
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
const infoRef = ref(null)
onMounted(()=>{
console.log(infoRef.value.count)
})
</script>
// 默认情况下 读取不到
// 子组件
<script setup lang="ts">
import { ref } from 'vue'
const count = ref(2)
</script>
// 使用 defineExpose 暴露出去
<script setup lang="ts">
import { ref } from 'vue'
const count = ref(2)
defineExpose({
count
])
</script>