Vue使用$attrs實現(xiàn)爺爺直接向?qū)O組件傳遞數(shù)據(jù)
前言
最近在重讀vue3文檔,讀到"#Class與Style綁定"這一章節(jié)時突然發(fā)現(xiàn),通過$attrs可以直接實現(xiàn)爺爺組件向?qū)O子組件傳遞數(shù)據(jù)。
不考慮注入依賴provide/inject和vuex的情況下,父子組件傳遞數(shù)據(jù)時最常用的是props,遇到爺傳孫的情況,會先爺傳父再父傳子,可以完成需求但總有點那啥,使用$attrs就可以直接實現(xiàn)爺傳孫,畢竟少寫一行代碼是一行啊。
實現(xiàn)
具體實現(xiàn)(以vue3為例):
<--爺組件-->
<script setup>
import { ref } from 'vue';
import Father from './components/Father.vue'
const fatherStr = ref('這是爸爸的數(shù)據(jù)')
const childStr = ref('這是孫子的數(shù)據(jù)')
</script>
<template>
<Father :fatherStr="fatherStr" :childStr='childStr'></Father>
</template>
爺組件向父組件和孫組件各傳遞了數(shù)據(jù),父組件代碼如下:
<--父組件-->
<script setup>
import Child from './child.vue'
</script>
<template>
<div>
<p >father</p>
<p>{{ $attrs.fatherStr }}</p>
<Child v-bind="$attrs"></Child>
</div>
</template>
孫組件代碼如下:
<--孫組件-->
<script setup>
</script>
<template>
<div>
<p >child</p>
<p>{{ $attrs.childStr }}</p>
</div>
</template>
最后頁面實現(xiàn)效果如下:

優(yōu)化
雖然實現(xiàn)了,但是通過閱讀Vue文檔可以發(fā)現(xiàn),他并不是響應式的。

對于不需要經(jīng)常變動的數(shù)據(jù)應該是夠用了,但是如果是響應式的數(shù)據(jù),可能會有問題,所以做了以下優(yōu)化。 爺組件不變,父組件和孫組件代碼分別如下。
<--父組件-->
<script setup>
import Child from './child.vue'
const props = defineProps(['fatherStr'])
</script>
<template>
<div>
<p >father</p>
<p>{{ fatherStr }}</p>
<Child v-bind="$attrs"></Child>
</div>
</template>
<style scoped>
</style>
<--孫組件-->
<script setup>
const props = defineProps(['childStr'])
</script>
<template>
<div>
<p >child</p>
<p>{{ childStr }}</p>
</div>
</template>
<style scoped>
</style>
效果還是一樣的:

到此這篇關(guān)于Vue使用$attrs實現(xiàn)爺爺直接向?qū)O組件傳遞數(shù)據(jù)的文章就介紹到這了,更多相關(guān)Vue $attrs組件傳遞數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用babel-plugin-import?實現(xiàn)自動按需引入方式
這篇文章主要介紹了使用babel-plugin-import?實現(xiàn)自動按需引入方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12
vue+element 實現(xiàn)商城主題開發(fā)的示例代碼
這篇文章主要介紹了vue+element 實現(xiàn)商城主題開發(fā)的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-03-03
vue+webpack模擬后臺數(shù)據(jù)的示例代碼
這篇文章主要介紹了vue+webpack模擬后臺數(shù)據(jù)的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07

