如果你想保持封装,那就没有了.伟大的父母不应该知道孩子.它知道祖父母,但不是有子组件或有多少.原则上,您可以将祖父母的一个实现换成另一个没有多个层的实现.或者有更多的层次来接触孩子.你可以把孩子放到顶级组件中.
您已经了解了全球事件总线的概念.不过,公共汽车不一定是全球性的.你可以把它传递给道具链. (您可以使用greatgrandparent本身作为公共汽车,但这会将其暴露给它的孩子;更好的卫生来制造真正的公共汽车.)
这将顶级组件与子组件区分开来:子组件将接收总线道具,以执行它有助于实现的顶级组件的功能.顶级组件将生成总线.
Vue.component('child', {
template: `
props: ['bus'],
methods: {
clicked: function() {
this.bus.$emit('clicked', 'hello');
},
},
});
Vue.component('parent', {
template: ``,
props: ['bus']
});
Vue.component('grandparent', {
template: ``,
props: ['bus']
});
Vue.component('greatgrandparent', {
template: ``,
data() {
return {
bus: new Vue()
};
},
created() {
this.bus.$on('clicked', this.clicked);
},
methods: {
clicked: function(msg) {
console.log('message from great grandchild: ' + msg);
},
},
});
new Vue({
el: '#app'
});