Javascript 如何从其他组件调用此组件方法';s事件侦听器($on)?
我在这里读过关于非亲子沟通的文章。听公交车事件的想法很清楚 但如何从总线侦听器调用其他组件的方法还不清楚。 例如,如何从eventHub.on('lst:additem',function())调用lst.additem2()? 这里的似乎有eventHub上下文(基于console.log(this.$data)结果) 这就是我的例子Javascript 如何从其他组件调用此组件方法';s事件侦听器($on)?,javascript,vue.js,vuejs2,vue-component,Javascript,Vue.js,Vuejs2,Vue Component,我在这里读过关于非亲子沟通的文章。听公交车事件的想法很清楚 但如何从总线侦听器调用其他组件的方法还不清楚。 例如,如何从eventHub.on('lst:additem',function())调用lst.additem2()? 这里的似乎有eventHub上下文(基于console.log(this.$data)结果) 这就是我的例子 Vue.component('lst', { template: ` <ul> <li v-for="(item, index
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' );
}
}
Vue.component('lst'{
模板:`
-
`,
已创建:函数(){
this.eventHub.$on('lst:additem',函数(d){
控制台日志(d);
console.log(this.$data.tip);
//此项。添加项2(d);此项不起作用:(
});
},
方法:{
Add项2:功能(新项){
log(“…此处”+newitem.weight);
此.items.push(newitem);
console.log('item added');
}
}
当您收听时,有关JSFIDLE的更多信息:
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);
});
@迪马福明对自己宽容,乐于助人。