How to create a global event bus in Vue.js?

To create a global event bus in Vue.js, you can follow these steps:

  1. Create a new Vue instance to act as the event bus. You can do this in a separate file called eventBus.js:
import Vue from 'vue' export const eventBus = new Vue()
  1. Import the event bus in the components where you want to use it:
import { eventBus } from './eventBus.js'
  1. Emit events from a component using the event bus:
methods: { onButtonClick() { eventBus.$emit('customEvent') } }
  1. Listen to events in another component using the event bus:
created() { eventBus.$on('customEvent', this.handleCustomEvent) }, methods: { handleCustomEvent() { // Handle the event here } }

With this setup, you can emit and listen to events across different components using the global event bus. Note that the event bus is global, so you can use it to communicate between unrelated components. However, keep in mind that using a global event bus can make it harder to trace and debug the flow of data in your application.