簡體   English   中英

如何從其他組件的事件監聽器($on)調用該組件方法?

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

我在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);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM