What is an event bus in VueJS
EventBus in Vue.js is a pattern used for communication between different components in a Vue.js application. It allows components to send and receive events without having a direct parent-child relationship.
In Vue.js, a centralized event bus can be created by using the Vue
constructor to create a new instance of a Vue instance specifically for the purpose of event communication. Components can then emit
events on this instance to signal other components, or listen
for events on it to handle incoming messages.
EventBus is useful when you want to pass data or trigger an action in a component that is not directly related to the component that initiated the action. By using an event bus, you can decouple the components and make the application more modular and scalable.
Here’s an example of how to create an event bus in Vue.js and use it to communicate between components:
// main.js
export const EventBus = new Vue();
// Component A
methods: {
someMethod() {
EventBus.$emit('some-event', this.data)
}
}
// Component B
created() {
EventBus.$on('some-event', (data) => {
// Handle event here
})
}