优点:不管多少层,都可以直接使用祖父节点的属性和方法
注意:
1. 如果属性是对象(比如testData2),那么是可以实现响应式变化,即祖父组件改变值,子孙组件都会相应变化
2. 如果属性是值(比如testData1),那么直接使用是无法实现响应式变化的,这时可以把testData1在provide里指定为用方法来获取
祖父:index.vue
data() {
return {
testData1: 0,
testData2: {count: 0},
}
}
provide(){
return {
Test: this.myTest,
Test2: this.myTest2,
data1: () => { return this.testData1 },
data2: this.testData2,
}
},
myTest(e){
console.log("myTest: ",e);
},
myTest2(e){
console.log("myTest2: ",e);
},
父组件:child.vue
// 啥都不用干
子组件:child.vue
<template>
<div>
<p>{{this.data1()}}</p>
<p>{{this.data2.count}}</p>
<el-button type="primary" @click.native="callGrandFather">调用祖父节点事件</el-button>
</div>
</template>
inject: {
Test: 'Test',
Test2: 'Test2',
data1: 'data1',
data2: 'data2',
},
created(){
console.log("我是dictTableTable,我的参数tableName=",this.tableName);
console.log("我是dictTableTable,我的参数tableName2=",this.tableName2);
},
methods: {
callGrandFather(){
this.Test(this.tableName)
this.Test2(this.tableName2)
}
}