Suppose I have a child component that want to send a message to a great grandparent, the code will be like this, correct me if I\'m wrong:
Vue.component(\'ch
Not if you want to maintain encapsulation. greatgrandparent
is not supposed to know about child
. It knows about grandparent
, but not that there are sub-components or how many. In principle, you can swap one implementation of grandparent
out for another that doesn't have multiple layers. Or has even more layers to get to child
. And you could put child
into a top-level component.
You already know about the notion of a global event bus. A bus doesn't have to be global, though. You can pass it down the props chain. (You could use greatgrandparent
itself as the bus, but that would expose it to its children; better hygiene to make a real bus.)
This distinguishes top-level components from sub-components: a sub-component will receive a bus
prop to perform the functions of the top-level component that it helps to implement. A top-level component will originate the bus.
Vue.component('child', {
template: `<div v-on:click="clicked">Click me</div>`,
props: ['bus'],
methods: {
clicked: function() {
this.bus.$emit('clicked', 'hello');
},
},
});
Vue.component('parent', {
template: `<child :bus="bus"></child>`,
props: ['bus']
});
Vue.component('grandparent', {
template: `<parent :bus="bus"></parent>`,
props: ['bus']
});
Vue.component('greatgrandparent', {
template: `<grandparent :bus="bus" v-on:clicked="clicked"></grandparent>`,
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'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<greatgrandparent id="app"></greatgrandparent>