JAVASCRIPT
Create a Reusable Global Event Bus with Mitt Composable in Vue 3
Implement a lightweight global event bus using the Mitt library and Vue 3 Composables, enabling decoupled communication between components.
// composables/useEventBus.js
import mitt from 'mitt';
const emitter = mitt();
export function useEventBus() {
return {
on: emitter.on, // Listen for an event
emit: emitter.emit, // Emit an event
off: emitter.off, // Stop listening for an event
};
}
// Component A (Emits Event) - e.g., EventSender.vue
<template>
<div>
<button @click="sendMessage">Send Message</button>
</div>
</template>
<script setup>
import { useEventBus } from '../composables/useEventBus'; // Adjust path
const { emit } = useEventBus();
function sendMessage() {
emit('custom-event', { message: 'Hello from Component A!' });
}
</script>
// Component B (Listens for Event) - e.g., EventReceiver.vue
<template>
<div>
<p>Received: {{ receivedMessage }}</p>
</div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { useEventBus } from '../composables/useEventBus'; // Adjust path
const { on, off } = useEventBus();
const receivedMessage = ref('No message yet.');
const handleCustomEvent = (payload) => {
receivedMessage.value = payload.message;
console.log('Event received:', payload);
};
onMounted(() => {
on('custom-event', handleCustomEvent);
});
onUnmounted(() => {
off('custom-event', handleCustomEvent);
});
</script>
// App.vue (Parent to host both components)
<template>
<div style="display: flex; gap: 20px;">
<EventSender />
<EventReceiver />
</div>
</template>
<script setup>
import EventSender from './components/EventSender.vue';
import EventReceiver from './components/EventReceiver.vue';
</script>
How it works: This snippet demonstrates creating a global event bus in Vue 3 using the lightweight `mitt` library wrapped in a composable. The `useEventBus.js` file initializes `mitt` once and exposes `on`, `emit`, and `off` methods. `Component A` uses `emit` to send a `custom-event` with a payload. `Component B` uses `on` to listen for the `custom-event`, updating its `receivedMessage` reactivity. Crucially, `onUnmounted` is used to call `off` and clean up the event listener, preventing memory leaks and ensuring proper component lifecycle management. This pattern allows for decoupled communication between components that are not directly related in the component tree.