Vue使用$attrs實(shí)現(xiàn)爺爺直接向?qū)O組件傳遞數(shù)據(jù)
前言
最近在重讀vue3文檔,讀到"#Class與Style綁定"這一章節(jié)時(shí)突然發(fā)現(xiàn),通過$attrs可以直接實(shí)現(xiàn)爺爺組件向?qū)O子組件傳遞數(shù)據(jù)。
不考慮注入依賴provide/inject和vuex的情況下,父子組件傳遞數(shù)據(jù)時(shí)最常用的是props,遇到爺傳孫的情況,會(huì)先爺傳父再父傳子,可以完成需求但總有點(diǎn)那啥,使用$attrs就可以直接實(shí)現(xiàn)爺傳孫,畢竟少寫一行代碼是一行啊。
實(shí)現(xiàn)
具體實(shí)現(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>
最后頁面實(shí)現(xiàn)效果如下:

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

對(duì)于不需要經(jīng)常變動(dòng)的數(shù)據(jù)應(yīng)該是夠用了,但是如果是響應(yīng)式的數(shù)據(jù),可能會(huì)有問題,所以做了以下優(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實(shí)現(xiàn)爺爺直接向?qū)O組件傳遞數(shù)據(jù)的文章就介紹到這了,更多相關(guān)Vue $attrs組件傳遞數(shù)據(jù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue3結(jié)合TypeScript項(xiàng)目開發(fā)實(shí)戰(zhàn)記錄
聽說有的公司已經(jīng)開始用vue3了 趕緊打開B站學(xué)一下,下面這篇文章主要給大家介紹了關(guān)于Vue3結(jié)合TypeScript項(xiàng)目開發(fā)實(shí)戰(zhàn)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2021-09-09
Vue.js系列之項(xiàng)目結(jié)構(gòu)說明(2)
這篇文章主要介紹了Vue.js系列之項(xiàng)目結(jié)構(gòu)說明(2)的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-01-01
解決vue的 v-for 循環(huán)中圖片加載路徑問題
今天小編就為大家分享一篇解決vue的 v-for 循環(huán)中圖片加載路徑問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-09-09
使用Vue-Router 2實(shí)現(xiàn)路由功能實(shí)例詳解
vue-router 2只適用于Vue2.x版本,下面我們是基于vue2.0講的如何使用vue-router 2實(shí)現(xiàn)路由功能,需要的朋友可以參考下2017-11-11

