23/11/24 学习总结
1.Vue3.2 ref子组件实例和defineExpose
如果要调用子组件的数据,需要先在子组件显示暴露出来,父组件才能够正确的拿到。
(1)子组件
<template>
<span>{
{person.name}}</span>
</template>
<script setup>
import { reactive, toRefs } from 'vue'
// person
const person = reactive({
name: 'Jack'
})
// 将方法、变量暴露给父组件使用,父组件才可通过ref API拿到子组件暴露的数据
defineExpose({
// 解构state
...toRefs(person),
// 声明方法
updataName () {
state.name = 'Rose'
}
})
</script>
(2)父组件
- 获取单个子组件实例
<template>
<child ref='childRef'/>
</template>
<script setup>
import { ref, nextTick } from 'vue'
// 引入子组件
import child from './child.vue'
// 子组件ref
const childRef = ref<InstanceType<typeof child>>()
nextTick(() => {
// 获取子组件name
console.log(childRef.value.name)
// 执行子组件方法
childRef.value.updataName()
})
</script>
-
获取多个子组件实例
通过下标来向 childRefs 添加/修改ÿ