[Vuejs]-Where to listen for events using eventBus in vuejs

0👍

You are not calling anything you are simply registering the event listener. Most of the time these event listeners can be set up as soon as possible so you can move your event listener to your created lifecycle hook since this will run earlier than the mounted hook.

The mounted hook is usually a good place to put code that requires the DOM template to be rendered. Most event listeners don’t need it because the event that they are listening to either fires when the DOM is ready(so it already does the check) or does not use it at all.

0👍

You’re fine to put your event listener in a lifecycle hook like created/mounted but remember to remove the listeners in the beforeDestroy lifecycle hook otherwise the listeners will hang around after the component has been destroyed.
You will emit an event somewhere else in your app (with the option of passing data) using:

eventBus.$emit('quoteAdded', data);

Then your listener will pick it up when it fires and execute the callback (in your example someFunc).

As an aside i have found that, with global event listeners, you have to be very careful which lifecycle hook you use to register them especially if you are potentially toggling between the same component.

For example i have a complex layout like this:

<componentA>
    <componentB v-if="flag"></componentB>
    <componentC v-else>This component has componentB inside it!!</componentC>
</componentA>

My global event listeners are registered in componentB. Note that componentB is also nested inside componentC and we toggle between the components using the flag.

When we toggle from componentA to componentC the following lifecycle hok events are called:

C (created) -> B (beforeDestroy) -> C (mounted)

In other words if you are registering your event listers in ‘created’ and removing them in ‘beforeDestroy’ then they will get removed as soon as they’re created.
If instead you use the ‘mounted’ hook then this is resolved (for this specific case). Bit longwinded but it tripped me up.

Leave a comment