我在这里读过有关非亲子沟通的内容https://v2.vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication 。监听总线事件的想法很明确。
但是目前还不清楚如何从总线监听器调用其他组件的方法。 例如,如何从 eventHub.$on('lst:additem', function() 调用 lst.additem2() ? 似乎其中的 this 具有 eventHub 上下文(基于 console.log( this.$data) 结果)。
这是我的例子
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' );
}
}
有关 JSFiddle 的更多信息 https://jsfiddle.net/0mx8mtcj/13/
最佳答案
当你在听的时候:
this.eventHub.$on('lst:additem', function(d) {
// `this` here refers to the bus instance
});
所以只需保存组件的引用即可:
var self = this;
this.eventHub.$on('lst:additem', function(d) {
self.additem2(d);
});
关于javascript - 如何从其他组件的事件监听器($on)调用此组件方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42351266/