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('child', {
template: `<div v-on:click="clicked">Click me</div>`,
methods: {
clicked: function () {
this.$emit('clicked', "hello")
},
},
});
Vue.component('parent', {
template: `<child v-on:clicked="clicked"></child>`,
methods: {
clicked: function (msg) {
this.$emit('clicked', msg)
},
},
});
Vue.component('grandparent', {
template: `<parent v-on:clicked="clicked"></parent>`,
methods: {
clicked: function (msg) {
this.$emit('clicked', msg)
},
},
});
Vue.component('greatgrandparent', {
template: `<grandparent v-on:clicked="clicked"></grandparent>`,
methods: {
clicked: function (msg) {
console.log('message from great grandchild: ' + msg);
},
},
});
Is there a possibility to directly intercept the message from the child and call the clicked function in the great-grandparent without the need to set up the passing callback at every parent?
I know I can use a custom databus, https://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication, but since my components have parent-child relationship already, shouldn't I be able to notify the grandparent in a simpler way?
Not if you want to maintain encapsulation.
greatgrandparent
is not supposed to know aboutchild
. It knows aboutgrandparent
, but not that there are sub-components or how many. In principle, you can swap one implementation ofgrandparent
out for another that doesn't have multiple layers. Or has even more layers to get tochild
. And you could putchild
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.