使用setup的组件是默认关闭的——即通过模板引用或者 $parent 链获取到的组件的公开实例,不会暴露任何在 中声明的绑定。
理解:组件中的数据(变量、方法、函数)默认情况下不能被其他组件或父组件调用、可以通过defineExpose()将属性暴露出去
具体使用方法
父组件:
<template>
<view>
<TestExpose ref="child"></TestExpose>
<text>---</text>
<button @click="add">点击增加</button>
</view>
</template>
<script setup>
import {onMounted, ref} from "vue"
const child = ref(null)
const add = ()=>{
child.value.toggleCount()
}
onMounted(()=>{
//字符串、对象等类型需要在页面挂载完成后才能打印出来
console.log(child.value.obj);
})
</script>
子组件:
<template>
<view>
测试expose组件--子组件
<text>-------</text>
{{count}}
</view>
</template>
<script setup>
import {ref} from "vue"
const obj = {
name:"dsq",
count:10,
}
const toggleCount = ()=>{
count.value++
}
const count = ref(99);
defineExpose({
count,//数字
name:'dsq',//字符串
obj,//对象
toggleCount//函数
})
</script>