//爺爺組件中
import { provide , ref?} from 'vue'
const money = ref (100)? ? ? ?//定義數據
provide( 'money' , money )? ? ?//提供數據給孫子組件
const changeMoney = ( m:number ) => {? ? ? //定義函數
? ? if (money) {
? ? ? ?money.value = money.value - m
? }
}
provide("changeMoney ",changeMoney)? ? //提供函數給孫子組件
// 孫子組件中
import { inject?} from 'vue'
const money = inject('money')? ? ?//獲取傳遞過來的數據
const changeMoney = inject<m:number> => viod ('changeMoney ')? //獲取傳遞過來的函數
舉例:如果在孫子組件中想要修改爺爺組件的數據
// 孫子組件中
<button @click="handleMoney">
import { inject?} from 'vue'
const money = inject< Ref<number> >('money')? ? ?//獲取數據
const?handleMoney=()=> {
? ? if(money) {? ? ? ? ? ? //在跨組件通信中,可能沒有傳值,所有這里做一個判斷
? ? ? ? ?money.value += 2
? }
}
?inject函數會默認將數據定義為unknown,所以這里需要定義一下傳過來數據的類型