vue Bus总线

有时候两个组件也需要通信(非父子关系)。当然Vue2.0提供了Vuex,但在简单的场景下,可以使用一个空的Vue实例作为中央事件总线。

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

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

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

在实际运用中,一般将Bus抽离出来:

Bus.js

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

组件调用时先引入

组件1

复制代码
import Bus from './Bus'

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

  }        
复制代码

组件2

复制代码
import Bus from './Bus'

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

但这种引入方式,经过webpack打包后可能会出现Bus局部作用域的情况,即引用的是两个不同的Bus,导致不能正常通信

 实际运用二(推荐):

当然也可以直接将Bus注入到Vue根对象中,

复制代码
import Vue from 'vue'
const Bus = new Vue()

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

})

 

转载于:https://www.cnblogs.com/weiwei-python/p/9590866.html

你可能感兴趣的:(vue Bus总线)