vue Bus总线

有时候两个组件也须要通讯(非父子关系)。固然Vue2.0提供了Vuex,但在简单的场景下,能够使用一个空的Vue实例做为中央事件总线。vue

参考:http://blog.csdn.net/u013034014/article/details/54574989?locationNum=2&fps=1webpack

例子:https://segmentfault.com/q/1010000007491994web

<div id="app">
    <c1></c1>
    <c2></c2>
</div>
 
var Bus = new Vue(); //为了方便将Bus(空vue)定义在一个组件中,在实际的运用中通常会新建一Bus.js
Vue.component('c1',{ //这里已全局组件为例,一样,单文件组件和局部组件也一样适用
template:'<div>{{msg}}</div>',
  data: () => ({
    msg: 'Hello World!'
  }),
  created() {
    Bus.$on('setMsg', content => { 
      this.msg = content;
    });
  }
});
Vue.component('c2',{
  template: '<button @click="sendEvent">Say Hi</button>',
  methods: {
    sendEvent() {
      Bus.$emit('setMsg', 'Hi Vue!');
    }
  }
});
var app= new Vue({
    el:'#app'
})

在实际运用中,通常将Bus抽离出来:segmentfault

Bus.jsapp

import Vue from 'vue'
const Bus = new Vue()
export default Bus

组件调用时先引入this

组件1spa

import Bus from './Bus'

export default {
    data() {
        return {
            .........
            }
      },
  methods: {
        ....
        Bus.$emit('log', 120)
    },

  }        

组件2.net

import Bus from './Bus'

export default {
    data() {
        return {
            .........
            }
      },
    mounted () {
       Bus.$on('log', content => { 
          console.log(content)
        });    
    }    
} 

但这种引入方式,通过webpack打包后可能会出现Bus局部做用域的状况,即引用的是两个不一样的Bus,致使不能正常通讯prototype

 运用二:插件

固然也能够直接将Bus注入到Vue根对象中,

import Vue from 'vue'
const Bus = new Vue()

var app= new Vue({
    el:'#app',
   data:{
    Bus
    }  

})

在子组件中经过this.$root.Bus.$on(),this.$root.Bus.$emit()来调用

运用三:

将bus挂载到vue.prototype上(这里用了插件的写法)

// plugin/index.js
import Bus from 'vue';
let install = function (Vue) {
    ... ...
    // 设置eventBus
    Vue.prototype.bus = new Bus();
    ... ...
}

export default {install};

// main.js
import Vue from 'vue';
import plugin from './plugin/index';
... ...

Vue.use(plugin);

... ...

组件一中定义

... ...
created () {
    this.bus.$on('updateData', this.getdata);
}

组件二中调用

this.bus.$emit('updateData', {loading: false});

 注意:注册的总线事件要在组件销毁时卸载,不然会屡次挂载,形成触发一次但多个响应的状况

beforeDestroy () {
        this.bus.$off('updateData', this.getData);
    }
相关文章
相关标签/搜索