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

FeatureProps/$emitEvent Bus
DirectionParent ↔ Child onlyAny component to any component
Best forDirect parent-child communicationSibling or distant component communication
ScalabilityScales wellCan 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)