Vue、nuxt配置全局事件总线

1,311 阅读1分钟

Vue配置$bus

在main.js中加入beforeCreate() {Vue.prototype.$bus = this;}

// main.js
new Vue({
  render: h => h(App),
  beforeCreate() {
      Vue.prototype.$bus = this;
  }
}).$mount('#app')

使用方法

created() {
    // 创建事件
    this.$bus.$on('demo',()=> {
            console.log('demo');
    })
},
mounted() {
    // 获取事件
    this.$bus.$emit('demo')
    // console.log(this.$bus.$off);
},
beforeDestroy() {
    // 销毁事件
    this.$bus.$off('demo')
}

在nuxt配置$bus

配置环境

// plugin-bus.js
import Vue from 'vue' // 或者使用mitt

export default (_, inject) => {
  inject('bus', new Vue())
}

绑定事件

this.$nuxt.$on('init', () => {
  console.log('init')
})

获取事件

this.$nuxt.$emit('init')