1.子组件
本人用的是vue3的setup语法糖,在子组件中需要引入defineExpose,然后在defineExpose中暴露你想让父组件获取的信息
import {ref,reactive,defineExpose } from 'vue'(引入defineExpose)
const data = reactive(["走过来人来人往", "不喜欢也得欣赏", "陪伴是最长情的告白"])
defineExpose({
data
})
2.父组件
在父组件中获取子组件所暴露的信息(注意钩子函数的生命周期,不能在setup中使用,因为此时子组件尚未被创建,所以获取到的值为undefine)
<!--使用子组件-->
<View ref="childView"></View>
<script lang='ts' setup >
import View from './components/View.vue'//引入子组件
import { ref,onMounted} from 'vue'//引入钩子函数
const childView = ref<any>()
onMounted(() => {//在钩子函数中使用
console.log(childView.value);
console.log(childView.value.data);
})
</script>
另附结果图一张