[Vuejs]-How to use migrate Vue 2 $on, $emit event bus to Vue3?

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

Leave a comment