To create a global event bus in Vue.js, you can follow these steps:
eventBus.js
:import Vue from 'vue'
export const eventBus = new Vue()
import { eventBus } from './eventBus.js'
methods: {
onButtonClick() {
eventBus.$emit('customEvent')
}
}
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.