vue3如何通過provide和inject實(shí)現(xiàn)多層級組件通信
vue3通過provide和inject實(shí)現(xiàn)多層級組件通信
父組件
<template>
<div>
<h1>我是父組件 {{num}}</h1>
<hr>
<child></child>
</div>
</template>
<script setup>
import child from './child.vue';
import { ref,provide } from 'vue';
let num = ref(520)
provide('parentNum',num)
</script>子組件
<template>
<div>
<h2>我是子組件</h2>
<hr>
<grandchild></grandchild>
</div>
</template>
<script setup>
import grandchild from './grandchild.vue';
</script>孫子組件
<template>
<div>
<h3>我是孫子組件</h3>
<p>這是爺爺?shù)闹?{{parentNum}}</p>
<button @click="handler">點(diǎn)擊我爺爺?shù)闹禍p100</button>
</div>
</template>
<script setup>
import { inject } from 'vue';
let parentNum = inject('parentNum')
const handler = () => {
parentNum.value -= 100
}
</script>
擴(kuò)展:
vue3 provide 和 inject 的用法 實(shí)現(xiàn)跨層級的組件通信
1.父組件利用 provide 提供數(shù)據(jù)也就是傳
<script setup>
import { provide, ref } from 'vue'
import son from './son.vue'
let msg = ref('xjj')
// 在父組件中將 msg 設(shè)置為依賴注入:能夠在所有的后代組件中使用這些數(shù)據(jù)
provide('msg', msg)
</script>
<template>
<h2>05-組合式API - 依賴注入</h2>
<h3>父組件</h3>
<div>msg: {{ msg }}</div>
<son></son>
</template>
<style></style>2.子組件通過 inject (子孫后代, 都可以拿到這個(gè)數(shù)據(jù))也就是收
<script setup>
import { inject } from 'vue'
import gson from './gson.vue'
let msg = inject('msg')
</script>
<template>
<h3>子組件</h3>
<div>msg: {{ msg }}</div>
<gson></gson>
</template>
<style></style>注意:為了給 provide/inject 添加響應(yīng)式,使用 ref 或 reactive
到此這篇關(guān)于vue3通過provide和inject實(shí)現(xiàn)多層級組件通信的文章就介紹到這了,更多相關(guān)vue3多層級組件通信內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue3 onMounted異步函數(shù)同步請求async/await實(shí)現(xiàn)
這篇文章主要為大家介紹了vue3 onMounted初始化數(shù)據(jù)異步函數(shù)/同步請求async/await實(shí)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07
vue3動(dòng)態(tài)加載對話框的方法實(shí)例
對話框是很常用的組件,在很多地方都會(huì)用到,下面這篇文章主要給大家介紹了關(guān)于vue3動(dòng)態(tài)加載對話框的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-03-03
vue2.0結(jié)合DataTable插件實(shí)現(xiàn)表格動(dòng)態(tài)刷新的方法詳解
這篇文章主要介紹了vue2.0結(jié)合DataTable插件實(shí)現(xiàn)表格動(dòng)態(tài)刷新的方法,結(jié)合具體項(xiàng)目實(shí)例形式分析了vue2.0結(jié)合DataTable插件實(shí)現(xiàn)表格動(dòng)態(tài)刷新過程中遇到的問題與相應(yīng)的解決方法,需要的朋友可以參考下2017-03-03
淺談vue項(xiàng)目4rs vue-router上線后history模式遇到的坑
今天小編就為大家分享一篇淺談vue項(xiàng)目4rs vue-router上線后history模式遇到的坑,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09
Vue數(shù)據(jù)監(jiān)聽方法watch的使用
這篇文章主要介紹了Vue數(shù)據(jù)監(jiān)聽方法watch的使用,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-03-03
詳解vue中父子組件傳遞參數(shù)props的實(shí)現(xiàn)方式
這篇文章主要給大家介紹了在vue中,父子組件傳遞參數(shù)?props?實(shí)現(xiàn)方式,文章通過代碼示例介紹的非常詳細(xì),對我們的學(xué)習(xí)或工作有一定的參考價(jià)值,需要的朋友可以參考下2023-07-07
vue項(xiàng)目實(shí)現(xiàn)圖片懶加載的簡單步驟
懶加載的好處在于減少服務(wù)器的壓力,在網(wǎng)絡(luò)比較慢的情況下,可以提前給這張圖片添加一個(gè)占位圖片,提高用戶的體驗(yàn),這篇文章主要給大家介紹了關(guān)于vue項(xiàng)目實(shí)現(xiàn)圖片懶加載的相關(guān)資料,需要的朋友可以參考下2022-09-09

