Mahmud Adam Mahmud Adam - 1 year ago 911
Javascript Question

Vue.js global event bus

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){
this.count = num;

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

I created my templates like so:

I'd like the
component to communicate the count to the
component. I am not sure what I am doing wrong in

Answer Source

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){
 this.count = num;

You should also check out if you want to manage global application states

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download