Manish B
Manish B

Reputation: 51

Vue.js: Global event bus is failing to catch the event

I am trying to create a global event bus to be emitted from Source.vue to be caught in Destination.vue. The latter component has to run a function when the event is caught.

Source.vue:

.then(() => {
    eventBus.$emit("fireMethod");
})

Destination.vue:

updated() {
  eventBus.$on("fireMethod", () => {
    this.reqMethod();
  });
}

main.js:

export const eventBus = new Vue();

I have also imported the main.js file in both of the components. But that doesn't seem to work as the event is not caught at all. What's wrong here? Thanks in advance

Upvotes: 0

Views: 1072

Answers (2)

junaid rasheed
junaid rasheed

Reputation: 161

To register global event bus you can use this in your main.js

Vue.prototype.$eventHub = new Vue();        //global event bus

And then in your components use it like

//on emit
this.$eventHub.$on('your-event',function(){});

//to emit
this.$eventHub.$emit('your-event',data);

Upvotes: 0

Riddhi
Riddhi

Reputation: 2244

The updated hook runs after data changes on your component and the DOM re-renders. Hence on the initial render your event listener is not registered as the event is not triggered at that time.

Kindly go through this fiddle to get a clear idea about vue components life cycle.

Hence in Destination.vue:

Your event hook should be mounted and not updated.

mounted() {
  eventBus.$on("fireMethod", () => {
    this.reqMethod();
  });
}

Upvotes: 1

Related Questions