Events API removedbreaking

Overview

$on, $off and $once instance methods are removed. Vue instances no longer implement the event emitter interface.

2.x Syntax

In 2.x, Vue instance could be used to trigger handlers attached imperatively via the event emitter API ($on, $off and $once). This was used to create event hubs to create global event listeners used across the whole application:

  1. // eventHub.js
  2. const eventHub = new Vue()
  3. export default eventHub
  1. // ChildComponent.vue
  2. import eventHub from './eventHub'
  3. export default {
  4. mounted() {
  5. // adding eventHub listener
  6. eventHub.$on('custom-event', () => {
  7. console.log('Custom event triggered!')
  8. })
  9. },
  10. beforeDestroy() {
  11. // removing eventHub listener
  12. eventHub.$off('custom-event')
  13. }
  14. }
  1. // ParentComponent.vue
  2. import eventHub from './eventHub'
  3. export default {
  4. methods: {
  5. callGlobalCustomEvent() {
  6. eventHub.$emit('custom-event') // if ChildComponent is mounted, we will have a message in the console
  7. }
  8. }
  9. }

3.x Update

We removed $on, $off and $once methods from Vue instance completely. $emit is still a part of the existing API as it’s used to trigger event handlers declaratively attached by a parent component

Migration Strategy

Existing event hubs can be replaced by using an external library implementing the event emitter interface, for example mittEvents API - 图1.

These methods can also be supported in compatibility builds.