湛江有幫公司做網(wǎng)站營銷型網(wǎng)站更受用戶歡迎的原因是
1.provide和inject相較于父子傳遞的不同在于provide,inject可以用于跨層級通信(通俗易懂的講就是可以實現(xiàn)爺孫之間的直接信息傳遞)。
1.跨層級傳遞數(shù)據(jù)
1.在頂層組件通過provide函數(shù)提供數(shù)據(jù)
2.底層組件通過inject函數(shù)獲取數(shù)據(jù)
演示一:跨層傳遞普通數(shù)據(jù)。
效果圖:
?
?
演示二:跨層傳遞動態(tài)數(shù)據(jù)。?
?
?效果圖:
3.最后附上源代碼:
爺爺組件App.vue
<script setup>
import Father from './components/Father.vue';
import { provide ,ref} from 'vue';//傳遞普通數(shù)據(jù)
provide('HairColor','black')//傳遞相應(yīng)式數(shù)據(jù)
const count=ref(100)
provide('count',count)//跨層級傳遞函數(shù)
provide('changeCount',(SonInfo)=>{count.value--console.log(SonInfo)
})
</script><template><div><h1>這個是爺爺</h1><father></father></div>
</template><style lang="scss" scoped></style>
父親組件Father.vue
<script setup>
import Son from './Son.vue';
</script><template><div><h2>這里是爸爸</h2><Son></Son></div>
</template><style lang="scss" scoped></style>
?孫子組件Son.vue
<script setup>
import { inject } from 'vue';
const HairColor=inject('HairColor')//
const count=inject('count')const ChangeCount=inject('changeCount')
const clickFn=()=>{ChangeCount('傳給父親的數(shù)據(jù)')
}
</script><template><div><h3>這里是兒子---爺爺頭發(fā)的顏色---{{HairColor}} 年齡為:{{count}}歲</h3><button @click="clickFn">年齡減一</button></div>
</template><style lang="scss" scoped></style>
?