How to handle global events in Vue.js?

You can use Vue.js to handle global events by creating a centralized event bus. This involves creating a new Vue instance that acts as an event bus, allowing components to emit and listen for events.

// event-bus.js
import Vue from 'vue';
export const EventBus = new Vue();

In a component:

// Component A
import { EventBus } from './event-bus.js';

export default {
  methods: {
    emitEvent() {
      EventBus.$emit('custom-event', 'Data from Component A');
    }
  }
};

In another component:

// Component B
import { EventBus } from './event-bus.js';

export default {
  mounted() {
    EventBus.$on('custom-event', data => {
      console.log('Received data in Component B:', data);
    });
  }
};

 

Post your Answer