Vue.js 3 Event Bus

前端 未结 3 2057
粉色の甜心
粉色の甜心 2020-12-10 05:52

How to create Event Bus in Vue 3?


In Vue 2, it was:

export const bus = new Vue();


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-10 06:24

    As suggested in official docs you could use mitt library to dispatch events between components, let suppose that we a sidebar and header which contains a button that close/open the sidebar and we need that button to toggle some property inside the sidebar component :

    in main.js import that library and create an instance of that emitter and define as a global property:

    Installation :

     npm install --save mitt
    

    Usage :

    import { createApp } from 'vue'
    import App from './App.vue'
    import mitt from 'mitt';
    const emitter = mitt();
    let app=createApp(App)
    app.config.globalProperties.emitter = emitter
    app.mount('#app')
    

    in header emit the toggle-sidebar event with some payload :

    
    
    
    

    In sidebar receive the event with the payload:

    
    
    

    For those using composition api they could use emitter as follows :

    import { getCurrentInstance } from 'vue'
    export default{
    
       setup(){
          const internalInstance = getCurrentInstance(); 
          const emitter = internalInstance.appContext.config.globalProperties.emitter;
    
           ...
         },
      ...
    
    }
    
    

提交回复
热议问题