[Vuejs]-Dynamically listen to custom event on parent component

0👍

Figured a way to do it without refactoring the individual components: just injected the listener in every component using a mixin.

The result:

// Before starting up the main instance:
Vue.mixin({
    created: function() {
        this.$on('error', function(error) {
            // Then I handled the errors here.
        );
    }
});
👤Ayrton

1👍

You can use the EventBus system in Vue instance. Actually EventBus is a different Vue instance your Main Vue instance. You make your own Event bus system.$emit, $on and $off events.

event-bus.js

import Vue from 'vue';
export const EventBus = new Vue();

and now you are ready to use.

some-component.vue

// Import the EventBus.
import { EventBus } from './event-bus.js';
// Send the event on a channel (eventName) with a payload (the click count.)
EventBus.$emit('eventName', this.clickCount);

other-component.vue

// Import the EventBus.
import { EventBus } from './event-bus.js';

// Listen for the eventName event and its payload.
EventBus.$on('eventName', clickCount => {
  console.log(clickCount)
});

// Stop listening.
EventBus.$off('eventName');

more information and example
https://alligator.io/vuejs/global-event-bus/

👤radoiz

Leave a comment