简体   繁体   English

如何从其他组件的事件监听器($on)调用该组件方法?

[英]How to call this component method from other component's event listener ($on)?

I've read about Non-Parent-Child Communication here https://v2.vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication .我在https://v2.vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication阅读了有关非父子通信的信息。 An idea with listening to bus events is clear.监听总线事件的想法很明确。

But it's still unclear how to call other components's methods from bus listener.但是目前还不清楚如何从总线监听器中调用其他组件的方法。 For example how can I call lst.additem2() from eventHub.$on('lst:additem', function() ? It seems that this in there has eventHub context (basing at console.log( this.$data) result ).例如,如何从eventHub.$on('lst:additem', function()调用lst.additem2( ) ?似乎里面的this有 eventHub 上下文(基于console.log(this.$data)结果) .

There is my example有我的例子

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' );
  }
}

more on JSFiddle https://jsfiddle.net/0mx8mtcj/13/更多关于 JSFiddle https://jsfiddle.net/0mx8mtcj/13/

When you are listening:当你在听时:

  this.eventHub.$on('lst:additem', function(d) { 
    // `this` here refers to the bus instance
  });

So just save a reference of the component:所以只需保存组件的引用:

var self = this;
this.eventHub.$on('lst:additem', function(d) { 
  self.additem2(d);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM