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

标签 javascript vue.js vuejs2 vue-component

我在这里读过有关非亲子沟通的内容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/

相关文章:

vue.js - nuxtjs 无法在生产环境中显示动态 url

javascript - vue.js 不适用于我的第一个测试 html 页面

vue.js - Vue - 从字符串中渲染一个元素

javascript - 使用 Javascript 和 PLV8 在 Postgresql 中计算重复事件

javascript - 如何将 ISO 8601 转换为美国时区

javascript - 如何从map()函数正确传递变量

javascript - 使用vue制作SPA但遇到一些麻烦

javascript - 异步 webpack 配置

javascript - 第一个 vue/webpack 应用程序,没有 webpack.config 文件

vue.js - Vite如何使用sass