Vue.js 3 event bus
P粉905144514
2023-08-24 18:08:45
<p>How to create an event bus in Vue 3? </p>
<hr />
<p>In Vue 2, it is: </p>
<pre class="brush:js;toolbar:false;">export const bus = new Vue();
</pre>
<pre class="brush:js;toolbar:false;">bus.$on(...)
bus.$emit(...)
</pre>
<hr />
<p>In Vue 3, <code>Vue</code> is no longer a constructor, and <code>Vue.createApp({});</code> returns a without <code>$ on</code> object code> and <code>$emit</code> methods. </p>
On Vue.js version 3, you can use third-party libraries or functions written in the publisher-subscriber (PubSub concept) programming pattern.
Event.js
index.js
As suggested in the official documentation , you can use the mitt library to dispatch events between components, assuming we have a sidebar and
header where Contains a button to close/open the sidebar, which we need to toggle certain properties within the sidebar component:
Import the library in main.js and create an instance of the emitter and define it as Global properties:
Install:
usage:
Emit a
toggle-sidebar
event with some payload in the header:Receive events with payload in the sidebar:
For those using the composition API, they can use
emitter
as follows:Create file src/composables/useEmitter.js
From there, you can use
useEmitter
just like you would useuseRouter
:Using the Combination API
You can also benefit from the new composition API and define composable event buses:
eventBus.js
Perform the following operations in component A:
In component B: