Introduction to Event Bus

In Vue.js, the Event Bus is a pattern for creating a global communication system between components. It allows components to communicate with each other without the need for direct parent-child relationships or prop drilling. In this guide, we'll explore how to use the Vue.js Event Bus effectively for global event handling.


Creating an Event Bus

To create an Event Bus in Vue.js, you can use a dedicated Vue instance as the central hub for emitting and listening to events. Here's an example of creating an Event Bus:


<script>
// Create a Vue instance as the Event Bus
const eventBus = new Vue();
// Export the Event Bus to be accessible in other components
export default eventBus;
</script>

In this example, we create a Vue instance named "eventBus" that serves as the global Event Bus. You can export this instance to make it available for other components.


Emitting and Listening to Events

Components can emit events and listen for events using the Event Bus. Here's an example of emitting an event from one component and listening to it in another:


<!-- ComponentA.vue -->
<template>
<button @click="emitEvent">Emit Event</button>
</template>
<script>
import eventBus from './eventBus';
export default {
methods: {
emitEvent: function() {
eventBus.$emit('custom-event', 'Event data from Component A');
}
}
};
</script>
<!-- ComponentB.vue -->
<template>
<div>
<p>{{ eventData }}</p>
</div>
</template>
<script>
import eventBus from './eventBus';
export default {
data() {
return {
eventData: ''
};
},
created() {
eventBus.$on('custom-event', data => {
this.eventData = data;
});
}
};
</script>

In this example, ComponentA emits a "custom-event" with data, and ComponentB listens for that event and updates its data accordingly.


Conclusion

Vue.js Event Bus is a powerful tool for enabling global event handling and communication between components. By creating a central hub for emitting and listening to events, you can build more modular and interconnected Vue applications that respond to events and data changes effectively.