Vue.js global event bus

后端 未结 4 1653
被撕碎了的回忆
被撕碎了的回忆 2020-12-31 04:40

I am trying to create a global event bus so that two sibling components can communicate with each other. I have searched around; however, I cannot find any examples of how t

4条回答
  •  余生分开走
    2020-12-31 05:28

    How about this? Assume Vue.js 2.

    Create a reusable Event-Bus component and attach it to Vue via plugin pattern:

    // ./components/EventBus.vue
    import Vue from 'vue'
    export const EventBus = new Vue()
    
    // ./plugins/EventBus.js
    export default {
      install(Vue) {
        const { EventBus } = require('../components/EventBus')
        Vue.prototype.$bus = EventBus
      }
    }
    
    // ./main.js
    import EventBus from './plugins/EventBus'
    Vue.use(EventBus)
    

    Then, you can do anywhere in your code: this.$bus.$emit('some-event', payload)

    As a side note, try to utilize the Event-Bus pattern as last resort.

提交回复
热议问题