If you were like me calling some event on this.$root.$on(...) and this.$root.$emit(...) in Vue2 from any parent/child to any child/parent for somehow keep your code cleaner rather then using bunch of emits and props respectively and have your code blows up..
from Vue3 doc, event bus pattern can be replaced by using an external library implementing the event emitter interface.
use a library that implement a pub-sub pattern or write it.
vue3 event description
Now if you're using the Option-API (like vue 2) y need to import that event file then using it right a way in any component.
if you are using the <script setup> you need add extra step in order to you that event library heres the code.
here's a basic example of pub-sub javascript pattern, don't forget to add the off method and call it on beforeUnmounted(v3), beforeDestroy(v2) to not have multiple function execution for each mounted call )
//event.js
class Event{
constructor(){
this.events = {};
}
on(eventName, fn) {
this.events[eventName] = this.events[eventName] || [];
this.events[eventName].push(fn);
}
emit = (eventName, data)=> (this.events[eventName]) ? this.events[eventName].forEach( fn => fn(data)) : '' ;
}
export default new Event();
if you're doing vue2 like syntax Option-API:
//in vue component
import event from './event';
//mounted or any methods
even.on('GG', data=> console.log(`GG Event received ${data}`))
//obviously you have to emit that from another component
//...
import event from './event';
//on mounted or methods click or...
even.emit('GG', {msg:"Vue3 is super Cool"});
if you're using the <script setup> which means all variables and methods are exposed by default to the template.
//in main.js
import event from './event.js';
//..
app.config.globalProperties.$event = event;
//..
//note if you have an error make sure that you split the the app chaining, like this :
let app = createApp(App);
app.config.globalProperties.$event = event;
app.mount('#app');
//add a file called useEvent.js
// useEvent.js
import { getCurrentInstance } from 'vue'
export default useEvent => getCurrentInstance().appContext.app.config.globalProperties.$event;
//using it in a <script setup>
import useEvent from '@/useEvent'
const event = useEvent();
event.emit('GG');