Creating a global event bus in Vue.js allows we to facilitate communication between components that are not directly related through parent-child or sibling relationships. Here’s how we can create a global event bus in Vue.js:
1. Create a new Vue instance
First, we create a new Vue instance to act as the event bus. This instance will be responsible for emitting and listening to events.
2. Export the event bus instance
We should export this instance so that other components can import and use it.
Here’s how we can implement it:
// EventBus.js
import Vue from 'vue';
// Create a new Vue instance to use as the event bus
const EventBus = new Vue();
// Export the event bus instance
export default EventBus;
Then, in our components, we can import the event bus and use it to emit and listen to events:
// ComponentA.vue
<template>
<button @click="emitEvent">Trigger Event</button>
</template>
<script>
import EventBus from './EventBus';
export default {
methods: {
emitEvent() {
// Emit an event
EventBus.$emit('custom-event', 'Data to send');
}
}
};
</script>
// ComponentB.vue
<script>
import EventBus from './EventBus';
export default {
created() {
// Listen to the event
EventBus.$on('custom-event', data => {
console.log('Event received:', data);
});
}
};
</script>
With this setup, ComponentA
emits an event when a button is clicked, and ComponentB
listens to this event and logs the data received.
This allows for communication between components without requiring a direct parent-child relationship.
Make sure to clean up event listeners when components are destroyed to prevent memory leaks.