如何从另一个组件事件监听器($on)调用这个组件方法?
How to call this component method from other component's event listener ($on)?
我在此处阅读了非亲子交流 https://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication。监听总线事件的想法很清楚。
但是还不清楚如何从总线监听器中调用其他组件的方法。
例如,如何从 eventHub.$on('lst:additem', function() 调用 lst.additem2() ?
似乎那里的 this 有 eventHub 上下文(基于 console.log( this.$data) result )。
有我的例子
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);
});
我在此处阅读了非亲子交流 https://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication。监听总线事件的想法很清楚。
但是还不清楚如何从总线监听器中调用其他组件的方法。 例如,如何从 eventHub.$on('lst:additem', function() 调用 lst.additem2() ? 似乎那里的 this 有 eventHub 上下文(基于 console.log( this.$data) result )。
有我的例子
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);
});