場景:當(dāng)我們需要將數(shù)據(jù)從父組件傳遞到子組件時钦无,通過props丛忆,但是如果有深嵌套的組件祠汇,再使用prop 傳遞到整個組件鏈中,會很麻煩
Vue3中 提供了provide 和 inject , 父組件可以作為其所有子組件的依賴項提供程序熄诡,而不管組件層次結(jié)構(gòu)有多深可很。這個特性有兩個部分:父組件有一個 provide 選項來提供數(shù)據(jù),子組件有一個 inject 選項來開始使用這個數(shù)據(jù)凰浮。
特點:
- 父組件不需要知道哪些子組件使用它提供的 property
- 子組件不需要知道
inject
property 來自哪里 - 如果需要屬性響應(yīng)式我抠,通過computed處理
案例
- src/components/inject.vue
<template>
<div>
inject1:
<injectcmp/>
</div>
</template>
<script>
import injectcmp from './inject2.vue'
export default {
components: {
injectcmp
},
// 注入祖父級屬性
inject: ['username'],
created(){
console.log('username === ', this.username);
}
}
</script>
- src/components/inject2.vue
<template>
<div>
inject2:
<!--
非響應(yīng)式屬性
數(shù)組長度:{{listlen}} -->
<!-- 響應(yīng)式屬性 -->
數(shù)組長度:{{listlen.value}}
</div>
</template>
<script>
export default {
// 注入祖父級屬性
inject: ['username', 'listlen'],
created(){
console.log('username2 === ', this.username, this.listlen);
}
}
</script>
- demo.vue
<!-- -->
<template>
當(dāng)前數(shù)組長度:{{list.length}}
<injectcmp/>
<br>
<button @click="btnclick">改變數(shù)組長度</button>
</template>
<script>
import injectcmp from'/@/components/inject.vue'
import { computed } from 'vue'
export default {
components: {
injectcmp
},
// 不能使用this對象
// provide: {
// username: 'uservalue'
// },
// 可以使用this對象
provide(){
return {
username: 'uservalue',
// 非響應(yīng)式屬性
// listlen: this.list.length
// 響應(yīng)式屬性
listlen: computed(()=>this.list.length)
}
},
methods: {
btnclick(){
this.list.push(6)
}
},
data () {
return {
list: [1,2,3,4,5]
}
}
}
</script>