Episode 25 of 44
The Event Bus
Use an event bus for communication between unrelated components — sibling-to-sibling communication without passing through the parent.
The Event Bus
Props and $emit work for parent-child communication. But what about sibling components or deeply nested components that need to talk? The event bus is a simple pattern for this.
Creating an Event Bus
// src/event-bus.js
import Vue from 'vue';
export const bus = new Vue();
The event bus is just an empty Vue instance. Components can emit events on it and listen for events from it.
Emitting on the Bus
<!-- ComponentA.vue -->
<script>
import { bus } from '../event-bus';
export default {
methods: {
changeTitle() {
bus.$emit('title-changed', 'New Title from Component A');
}
}
};
</script>
Listening on the Bus
<!-- ComponentB.vue -->
<script>
import { bus } from '../event-bus';
export default {
data() {
return { title: 'Original Title' };
},
created() {
bus.$on('title-changed', (newTitle) => {
this.title = newTitle;
});
}
};
</script>
Event Bus vs Props/$emit
| Feature | Props/$emit | Event Bus |
|---|---|---|
| Direction | Parent ↔ Child only | Any component to any component |
| Best for | Direct parent-child communication | Sibling or distant component communication |
| Scalability | Scales well | Can get messy in large apps — use Vuex instead |
Key Takeaways
- The event bus is an empty Vue instance used for cross-component communication
bus.$emit('event', data)sends events;bus.$on('event', callback)listens- Use it for sibling communication; for larger apps, consider Vuex (state management)