JAVASCRIPT
Building a Custom Event Bus for Cross-Component Communication in Vue 3
Implement a lightweight global event bus using a simple library like `mitt` in Vue 3 for flexible, decoupled communication between unrelated components.
<script setup>
import { onMounted, onUnmounted, ref } from 'vue';
import mitt from 'mitt';
// Create an event bus instance
const emitter = mitt();
// Expose the emitter globally (optional, but common for event buses)
// Or better: provide/inject it or create a composable if strictly typed communication is desired
// For this example, we'll demonstrate direct usage or via a shared file
// Component A: Emits an event
const emitEvent = () => {
const data = 'Data from Component A';
emitter.emit('custom-event', data);
console.log('Component A emitted custom-event with:', data);
};
// Component B: Listens for an event
const receivedData = ref(null);
onMounted(() => {
// Listen for the 'custom-event'
emitter.on('custom-event', (data) => {
receivedData.value = data;
console.log('Component B received custom-event with:', data);
});
});
onUnmounted(() => {
// It's crucial to unregister event listeners to prevent memory leaks
emitter.off('custom-event');
console.log('Component B unregistered custom-event listener.');
});
// Another component (e.g., Component C) could also use the same `emitter` instance
// to send or receive events.
</script>
<template>
<div>
<h3>Component A (Emitter)</h3>
<button @click="emitEvent">Emit Custom Event</button>
<h3>Component B (Listener)</h3>
<p v-if="receivedData">Received: {{ receivedData }}</p>
<p v-else>Waiting for event...</p>
<p style="margin-top: 20px; font-style: italic;">Note: In a real app, `emitter` would be imported from a shared utility file.</p>
</div>
</template>
How it works: This snippet demonstrates creating a lightweight event bus in Vue 3 using the `mitt` library. An event bus allows components that don't have a direct parent-child relationship to communicate by emitting and listening for custom events. Component A emits an event, and Component B listens for it, updating its state accordingly. It's crucial to use `onUnmounted` to clean up event listeners to prevent memory leaks and ensure proper resource management.