1.父组件代码
主要用 ref<InstanceType<typeof 组件>>() 来获取各个子组件实例
注意事项:
setup中的变量feature和world 一定要和上面标签上ref后面的一致,不然拿到的是空的,很重要!很重要!
<template> <div class="father"> <MyWorld ref="world"/> <Feature ref="feature" /> </div> <div @click="change">改变事件</div> </template> <script lang="ts"> import { defineComponent,onMounted } from 'vue' import { ref } from 'vue' import Feature from './Feature.vue' import MyWorld from './myWorld.vue' export default defineComponent({ components:{ MyWorld, Feature }, setup(){ // 要定义在外面,然后return出去 // feature和world 一定要和上面标签上ref后面的一致,不然拿到的是空的,很重要!很重要! const world = ref<InstanceType<typeof MyWorld>>() //泛类型 <typeof HelloWorld>的HelloWorld是组件 const feature = ref<InstanceType<typeof Feature>>() // 使用的时候在 onMounted里面 或者 其他方法里面 ,不然子组件的dom没加载完毕,就获取不到 onMounted(() => { // 改变前 console.log('改变前1',world.value); console.log('改变前2',feature.value); }) const change = () =>{ // 改变子组件的值 world.value!.msg = '你好,我的世界!' // !为断言,防止为空报错 feature.value!.plan = '你好,我的未来!' // 改变后 console.log('改变后1',world.value); console.log('改变后2',feature.value); // 调用子组件的方法,也可以不用问号,可以传参 world.value?.seyHello('1111') feature.value?.toDraw('2222') } return {feature,world,change} } }) </script>
2.子组件1 - MyWorld
<template> <div class="world"> <h1>{{ msg }}</h1> </div> </template> <script lang="ts"> import { defineComponent } from 'vue' import { ref,toRaw } from 'vue' export default defineComponent({ setup(){ let msg = ref('我的世界'); const seyHello = (str:string) => { console.log(msg.value + str); } return { msg,seyHello } } }) </script>
3.子组件2 - Feature
<template> <div class="feature"> <h1>{{ plan }}</h1> </div> </template> <script lang="ts"> import { defineComponent } from 'vue' import { ref,toRaw } from 'vue' export default defineComponent({ setup(){ let plan = ref('我的未来'); const toDraw = (str:string) => { console.log( plan.value + str ); } return { plan,toDraw } } }) </script>
4.父组件改变子组件值结果
5.父组件调用子组件方法输出结果