$on
, $off
And $once
instance methods are deleted. These three event interfaces are no longer implemented on the instance (the core is the encapsulation of event triggering and event listener functions).
2.x syntax
In 2.x, Vue instances can use event APIs ( $on
, $off
and $once
) to force additional processing code logic. This is used to create a listener function to create a global event listener used throughout the application:
// eventHub.js
const eventHub = new Vue()
export default eventHub
// ChildComponent.vue
import eventHub from './eventHub'
export default {
mounted() {
// adding eventHub listener
eventHub.$on('custom-event', () => {
console.log('Custom event triggered!')
})
},
beforeDestroy() {
// removing eventHub listener
eventHub.$off('custom-event')
}
}
// ParentComponent.vue
import eventHub from './eventHub'
export default {
methods: {
callGlobalCustomEvent() {
eventHub.$emit('custom-event') // if ChildComponent is mounted, we will have a message in the console
}
}
}
3.x update
Vue3 completely removed from the instance $on
, $off
and $once
methods. $emit
It is still part of the existing API because it is used to trigger events that are attached declaratively by the parent component.
Third party library
Vue3 does not support eventBus, so the official recommended approach is to use third-party libraries: