Vue.js全球活动巴士 [英] Vue.js global event bus

查看:82
本文介绍了Vue.js全球活动巴士的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个全局事件总线,以便两个兄弟组件可以相互通信。我四处寻找;但是,我找不到任何实现方法的例子。这就是我到目前为止:

I am trying to create a global event bus so that two sibling components can communicate with each other. I have searched around; however, I cannot find any examples of how to implement one. This is what I have so far:

var bus = new Vue();

Vue.component('Increment', {
  template: "#inc",
  data: function() {
   return ({count: 0})
  },
  methods: {
    increment: function(){
      var increment = this.count++
      bus.$emit('inc', increment)
  }
 }
})

Vue.component('Display', {
  template: "#display",
  data: function(){
  return({count: 0})
  },
 created: function(){
   bus.$on('inc', function(num){
   alert(num)
   this.count = num;
  });
 }
})


vm = new Vue({
 el: "#example",
})

我创建了我的模板如下: http://codepen.io/p-adams/pen/PzpZBg

I created my templates like so: http://codepen.io/p-adams/pen/PzpZBg

我希望 Increment 组件将计数传达给 Display 组件。我不知道我在总线上做错了什么。$ on()

I'd like the Increment component to communicate the count to the Display component. I am not sure what I am doing wrong in bus.$on().

推荐答案

问题在于你的总线。$ on 函数, 指的是公交车。您只需要使用 .bind()将当前Vue实例绑定到该函数:

The problem is that within your bus.$on function, this refers to the bus. You just need to bind the current Vue instance to that function using .bind():

bus.$on('inc', function(num){
 alert(num)
 this.count = num;
}.bind(this));

你还应该看看 https://github.com/vuejs/vuex 如果你想管理全球申请状态。

You should also check out https://github.com/vuejs/vuex if you want to manage global application states.

编辑:因为这个根据ChristopheMarois的评论,页面似乎得到了很多我想编辑的点击并添加了另一种方法:

Since this page seems to get a lot of clicks I want to edit and add another method, per ChristopheMarois in the comments:

bus.$on('inc', (num) => {
 alert(num);
 this.count = num;
});

或删除提醒:

bus.$on('inc', (num) => this.count = num);

这篇关于Vue.js全球活动巴士的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆