JAVASCRIPT

Implementing a Global Event Bus for Cross-Component Communication

Learn to use mitt for a simple global event bus in Vue 3, enabling efficient communication between loosely coupled components without prop drilling.

// src/plugins/eventBus.js
import mitt from 'mitt';
const emitter = mitt();
export default emitter;

// src/components/ComponentA.vue
<template>
  <button @click="sendMessage">Send Message</button>
</template>

<script setup>
import emitter from '../plugins/eventBus';

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

// src/components/ComponentB.vue
<template>
  <p>Received: {{ message }}</p>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import emitter from '../plugins/eventBus';

const message = ref('No message yet');

onMounted(() => {
  emitter.on('custom-event', (payload) => {
    message.value = payload;
  });
});

onUnmounted(() => {
  emitter.off('custom-event'); // Clean up listener
});
</script>
How it works: This snippet demonstrates how to set up and use a global event bus in Vue 3 using the `mitt` library. `ComponentA` emits a 'custom-event' with a payload when a button is clicked. `ComponentB` listens for this event upon mounting and updates its local state with the received message. It's crucial to unregister event listeners in `onUnmounted` to prevent memory leaks, ensuring a clean and efficient application.

Need help integrating this into your project?

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

Hire DigitalCodeLabs