In Vue.js 3, the concept of an event bus, which was commonly used in Vue 2, can be implemented using a more modern and recommended approach involving the mitt library or the Vue 3 provide and inject features. The event bus is used to facilitate communication between components that do not have a direct parent-child relationship.
mitt is a tiny (~200 bytes) event emitter library that can be used to create an event bus in Vue 3. Here’s how you can set it up:
Install mitt:
First, install the mitt library using npm or yarn.
npm install mitt # or yarn add mitt
Create the Event Bus:
Create a separate file (e.g., eventBus.js) to initialize and export the event bus.
// eventBus.js import mitt from 'mitt'; const emitter = mitt(); export default emitter;
Use the Event Bus in Components:
Parent Component: Where the event bus will be injected and provided to its children.
Child Component: Emit an event.
Sibling Component: Listen for the event.
{{ message }}
Installing mitt:
This way, you can facilitate communication between sibling components using an event bus in Vue.js 3 with the help of the mitt library.