多层级嵌套的组件,使用依赖注入provide 和 inject
父组件
提供数据
当点击按钮时,祖先组件提供getKey(写成函数形式,可响应)
<button @click="add">+1</button>
provide() {
return { getKey:()=> {
return this.keyvalue
}}
},
data() {
return {
keyvalue: 1,
}
},
methods: {
add() {
this.keyvalue = this.keyvalue + 1;
},
}
后代组件 引入数据
页面显示
后代页面显示 --{{ getKey() }}
inject: ['getKey'],