0

How can I transform this VueJS v2 code to v3?

window.Eventing = new (class {
    constructor() {
        this.vue = new Vue();
    }
    fire(event, data = null, subdata = null) {
        this.vue.$emit(event, data, subdata);
    }
    listen(event, callback) {
        this.vue.$on(event, callback);
    }
})();
entio
  • 3,816
  • 1
  • 24
  • 39
user1469734
  • 851
  • 14
  • 50
  • 81
  • 2
    There is a migration guide for Vue 2 to Vue 3, which specifically states that Vue3 no longer supports this use case of Vue as an event bus. https://v3.vuejs.org/guide/migration/events-api.html#migration-strategy – Excalibaard Apr 28 '21 at 15:10

1 Answers1

3

Vue 3 no longer supports the event emitting API from its prototype (including $emit and $on), but you could switch to a different event emitter library, such as tinyemitter (good for CDN usage) or tiny-emitter, which has a close API to the original in Vue 2:

import TinyEmitter from 'tinyemitter'

window.Eventing = new (class {
    constructor() {
        this.emitter = new TinyEmitter();
    }
    fire(event, data = null, subdata = null) {
        this.emitter.emit(event, data, subdata);
    }
    listen(event, callback) {
        this.emitter.on(event, callback);
    }
})();

demo

tony19
  • 125,647
  • 18
  • 229
  • 307