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.父組件調用子組件方法輸出結果