1

I'm trying to create an event bus setup in Vuejs 3 using mitt. I am following this Stackoverflow solution Vue.js3 Event Bus but it's not working. Here is my setup:

// main.js
import { createApp } from 'vue'
import App from './App.vue'
import mitt from 'mitt'

const emitter = mitt()
createApp(App).config.globalProperties.emitter = emitter

createApp(App).use(store).use(router).mount('#app')
// fire emitter event
emitFunction(){
  this.emitter.emit('hideMenu', true)
},
// listening for emitter
mounted(){
  this.emitter.on('hideMenu', (state) => {console.log(state)})
}

However, I get the following error: Uncaught TypeError: this.emitter is undefined

PS. It is not the same problem as this other question where the problem is how to access 'this' inside a callback: How to access the correct `this` inside a callback

alkadelik
  • 526
  • 1
  • 7
  • 18

2 Answers2

1

It is possible that you are creating the app twice and therefore, invalidating the initial config you set. In fact it is the second instance of createApp that you mounted, which doesn't contain the config you set.

Try putting the created app into a variable and then configure it.

See below.

const emitter = mitt()
const app = createApp(App)

app.config.globalProperties.emitter = emitter
app.use(store).use(router).mount('#app')
scartag
  • 17,548
  • 3
  • 48
  • 52
0

Create file like EventBus.ts:

import mitt from "mitt";

export default mitt()

And import EventBus where needed.

rilale
  • 1