Skip to content
Advertisement

Vue 3 Event Bus with Composition API

I have setup mitt and trying to dispatch event to another component but I am having hard time because in the setup() method it doesn’t have this for accessing app instance.

Here is what I tried:

JavaScript

And in the component, I want to dispatch an event

JavaScript

As this doesn’t exist, I can’t access the .emitter. What am I missing? How to use officially suggested mitt in Vue 3 composition api?


By the way if I use the v2 syntax, I can access this.emitter. But I am curious about Composition API way

JavaScript

Advertisement

Answer

To use an event bus in Vue 3 Composition API, use Vue 3’s new provide api in main.js, and then inject in any component:

1. Install mitt:

JavaScript

2. Provide:

main.js

JavaScript

3. Inject

3a. Any ComponentEmit an event

JavaScript

Call mymethod from a button click or something.

3b. Any ComponentListen for the event

JavaScript

Console

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement