I recently came across information on Non-Parent-Child Communication at https://v2.vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication, which explains the concept of using bus events to communicate between components.
However, I'm still unsure about how to call methods from other components within a bus listener. For example, how can I invoke lst.additem2() from eventHub.$on('lst:additem', function()? It seems like the context of this inside that function refers to the eventHub instead (as indicated by the console.log( this.$data) result).
Here is an example code snippet:
Vue.component('lst', {
template: `
<ul>
<li v-for="(item, index) in items" :good='item' :key="item.id">
<item :it='item' :index="index" ></item>
</li>
</ul>`,
created: function () {
this.eventHub.$on('lst:additem', function(d) {
console.log( d );
console.log( this.$data.tip );
// this.additem2(d); this won't work :(
});
},
methods: {
additem2 : function(newitem) {
console.log( '...here '+newitem.weight );
this.items.push( newitem );
console.log( 'item added' );
}
}
For more details, you can visit this JSFiddle link: https://jsfiddle.net/0mx8mtcj/13/