JAVASCRIPT
Implementing a Global Event Bus with `mitt` in Vue 3
Learn how to set up a lightweight global event bus using the `mitt` library in Vue 3 Composition API to facilitate communication between unrelated components without prop drilling.
// utils/eventBus.js
import mitt from 'mitt';
const emitter = mitt();
export default emitter;
// ComponentA.vue
// <template>
// <button @click="sendMessage">Send Message</button>
// </template>
//
// <script setup>
// import eventBus from '../utils/eventBus';
//
// function sendMessage() {
// eventBus.emit('my-event', 'Hello from ComponentA!');
// }
// </script>
// ComponentB.vue
// <template>
// <p>Received: {{ message }}</p>
// </template>
//
// <script setup>
// import { ref, onMounted, onUnmounted } from 'vue';
// import eventBus from '../utils/eventBus';
//
// const message = ref('No message yet.');
//
// onMounted(() => {
// eventBus.on('my-event', (payload) => {
// message.value = payload;
// console.log('ComponentB received:', payload);
// });
// });
//
// onUnmounted(() => {
// eventBus.off('my-event'); // Removes all listeners for 'my-event'
// // Or eventBus.off('my-event', specificHandler); if you need to remove a particular one
// });
// </script>
How it works: This snippet illustrates how to establish a global event bus in Vue 3 using the tiny `mitt` library. It's an effective pattern for communication between components that are not directly related (e.g., parent-child) without resorting to prop drilling or a full-blown state management solution. One component can `emit` an event with a payload, while another component `on`s that event to react to it. It's crucial to use `onMounted` to register listeners and `onUnmounted` to clean them up, preventing memory leaks.