Search code examples
javascriptvue.jseventemitteremit

How to make vue file listen (mitt's emitter.on) to emitter.emit event from an external js file?


My issue is I have an external file, would like to emit an event that is accessible by Vue file.

external.js:

import mitt from 'mitt';
const emitter = mitt();

function transaction(){
  emitter.emit('TRANSACTION_CONFIRMED_NOTIFICATION', true)
}

vue file:

const internalInstance = getCurrentInstance();
const emitter = internalInstance.appContext.config.globalProperties.emitter;
setup(){    
  emitter.on("TRANSACTION_CONFIRMED_NOTIFICATION", payload => {
     console.log('notify ' + payload);
  });
}

May I know how do make it work?


Solution

  • Your Vue file and external script need to use the same emitter instance for event listening to work between them.

    If you have control of the external script, export the emitter instance so that the Vue file could import it:

    external.js:

    export const emitter = mitt()
    
    //...
    

    Vue file:

    import { emitter } from './external'
    
    export default {
      setup() {
        emitter.on(/*...*/)
      }
    }