JAVASCRIPT

Implement a Global Event Bus with Mitt for Cross-Component Communication

Create an efficient global event bus in Vue 3 using the `mitt` library. Facilitates lightweight, many-to-many communication between decoupled components.

// plugins/eventBus.js
import mitt from 'mitt';

const emitter = mitt();

export const useEventBus = () => {
  return {
    emit: emitter.emit,
    on: emitter.on,
    off: emitter.off,
  };
};

/*
// main.js (for global availability, optional but common)
import { createApp } from 'vue';
import App from './App.vue';
import { useEventBus } from './plugins/eventBus';

const app = createApp(App);

// Make the event bus available globally via provide/inject
app.provide('eventBus', useEventBus());

app.mount('#app');

// Component A (Emitting an event)
<script setup>
import { inject } from 'vue';

const eventBus = inject('eventBus');

const sendMessage = () => {
  eventBus.emit('my-custom-event', 'Hello from Component A!');
};
</script>

<template>
  <div>
    <h2>Component A</h2>
    <button @click="sendMessage">Send Message</button>
  </div>
</template>

// Component B (Listening to an event)
<script setup>
import { inject, onMounted, onUnmounted, ref } from 'vue';

const eventBus = inject('eventBus');
const receivedMessage = ref('');

const handleCustomEvent = (payload) => {
  receivedMessage.value = payload;
  console.log('Component B received:', payload);
};

onMounted(() => {
  eventBus.on('my-custom-event', handleCustomEvent);
});

onUnmounted(() => {
  eventBus.off('my-custom-event', handleCustomEvent);
});
</script>

<template>
  <div>
    <h2>Component B</h2>
    <p v-if="receivedMessage">Received: {{ receivedMessage }}</p>
    <p v-else>Waiting for message...</p>
  </div>
</template>
*/
How it works: While Vue 3 generally promotes a prop-down/event-up communication pattern, a global event bus can be useful for communicating between entirely unrelated components or for handling global events. This snippet demonstrates how to set up a lightweight event bus using the `mitt` library. It's provided globally via `app.provide` in `main.js` and injected into components using `inject`. Components can then `emit` events or `on` (listen to) events, facilitating decoupled communication. Remember to `off` (unsubscribe) from events in `onUnmounted` to prevent memory leaks.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs