网上很多文章都是用父组件通过ref定义子组件实例,通过调用实例获得子组件的数据和方法:
子组件:
<script setup>
const test = () => {
console.log('子组件的方法1.....')
};
</script>
父组件:
<template>
<ChildrenComp ref='childRef'/>
</template>
<script setup>
import { ref } from 'vue'
const childRef = ref()
// 调用子组件的方法
childRef.value.test()
</script>
但这样往往控制台会报错,提示children.value.test() is not a function,这是因为使用 <script setup> 的组件是默认关闭的——即通过模板引用或者 $parent 链获取到的组件的公开实例,不会暴露任何在 <script setup> 中声明的绑定。
可以通过 defineExpose 编译器宏来显式指定在 <script setup> 组件中要暴露出去的属性:
子组件:
<script setup>
const test = () => {
console.log('子组件的方法1.....')
};
defineExpose({
test
})
</script>
这样父组件调用子组件内的方法和属性了。