JAVASCRIPT

Type-Safe Global Event Bus with mitt in Vue 3

Create a robust and type-safe global event bus in Vue 3 using the `mitt` library, enabling flexible communication between loosely coupled components.

// services/eventBus.ts (or .js)
import mitt, { Emitter, EventType } from 'mitt'

// Define your event types and their payloads
interface ApplicationEvents {
  'user-logged-in': { userId: string, username: string };
  'item-added-to-cart': { itemId: string, quantity: number };
  'show-notification': string; // Payload is a string message
}

const emitter: Emitter<ApplicationEvents> = mitt<ApplicationEvents>()

// Export methods for ease of use and type safety
export const emit = emitter.emit
export const on = emitter.on
export const off = emitter.off

// Usage in a component:
// <script setup lang="ts">
// import { onMounted, onUnmounted } from 'vue'
// import { on, emit } from '@/services/eventBus' // Adjust path as needed

// onMounted(() => {
//   on('user-logged-in', (payload) => {
//     console.log('User logged in:', payload.username, payload.userId)
//   })
//   on('show-notification', (message) => {
//     alert(message)
//   })
// })

// onUnmounted(() => {
//   off('user-logged-in') // Optional: remove specific handler
//   off('show-notification') // Optional: remove specific handler
//   // If you only need to remove a specific handler function, pass it as the second arg:
//   // off('user-logged-in', myHandlerFunction)
// })

// const loginUser = () => {
//   // ... login logic ...
//   emit('user-logged-in', { userId: '123', username: 'john_doe' })
//   emit('show-notification', 'Welcome, John Doe!')
// }
// </script>
How it works: This snippet demonstrates how to set up a type-safe global event bus in Vue 3 using the `mitt` library. By defining an `ApplicationEvents` interface, you ensure strong typing for event names and their corresponding payloads, preventing common errors. Components can then `emit` events with specific data, and other components can `on` listen to these events, facilitating communication across distant parts of your application without prop drilling or complex state management. It also highlights the importance of unregistering listeners with `off` 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