vue Bus总线

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

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

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

<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抽离出来:

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
    }  

})
复制代码

在子组件中通过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);
    }

 

posted @   fanlinqiang  阅读(49539)  评论(6编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示