Creating an eventBus in main.js:
Vue.prototype.$eventHub = new Vue()
In component1:
this.$eventHub.$emit('logged-in')
Attempting to use the event in component2:
beforeMount () {
this.$eventHub.$on('logged-in', function () {
console.log("logged in")
})
},
beforeDestroy() {
this.$eventHub.$off('logged-in')
}
The console is not showing anything. If I remove this.$eventHub.$off('logged-in')
, it works but runs multiple times based on how many times $emit
is called. What could be going wrong? Why is $off
not working?
Also facing issues passing parameters when using $emit
:
this.$eventHub.$emit('logged-in', "some message")
In $on
:
this.$eventHub.$on('logged-in', this.testEvent)
The method testEvent shows undefined for params.
However, using an arrow function seems to work:
this.$eventHub.$on('logged-in', (params) => {
console.log(params)
})
How can I effectively pass parameters to the method?