vue2、vue3 eventbus实现组件间全局通信

vue2

//在main.js
Vue.prototype.$eventBus=new Vue();

//传值组件
this.$eventBus.$emit('eventTarget',data)//data是需要通信的数据

//接收组件
this.$eventBus.$on('eventTarget',(res)=>{
	console.log(res);//具体需要操作的方法
})
//移除监听(为了避免路由切换过程中造成事件多次被绑定,多次触发,需要在适当的时机 off 掉)
this.$eventBus.$off("eventTarget")

vue3
eventBus vue3中没有了,要自己写
bus.js:

class Bus {
    constructor() {
        this.list = {};  // 收集订阅
    }
    // 订阅
    $on(name, fn) {
        this.list[name] = this.list[name] || [];
        this.list[name].push(fn);
    }
    // 发布
    $emit(name, data) {
        if (this.list[name]) {
            this.list[name].forEach((fn) => {    fn(data);   });
        }
    }
    // 取消订阅
    $off(name) {
        if (this.list[name]) {
            delete this.list[name];
        }
    }
}
export default new Bus;

调用订阅

<template>
    <button @click="fabu">发布</button>
</template>
<script>
import Bus from '../eventBus/Bus.js'
export default {
  setup() {
     function fabu(){
        Bus.$emit('addAge',{age:'19'});
     }
   }
 }
</script>

监听和卸载订阅

<template>
  <div>
    {{ name }} --- {{ age }}
  </div>
</template>
<script>
import {ref , onUnmounted} from 'vue';
import Bus from '../bus/bus.js';
export default {
  setup() {
       const name = '张三';
       const age = ref(18)
       Bus.$on('addAge',({ num })=>{    age.value = num;    })//监听
        
       //组件卸载时,取消订阅
       onUnmounted( () => { Bus.$off('addAge') } )//卸载
       //在离开组件(onUnmounted)时 ,将注册进去的 ,订阅函数的数组删除,避免存放越来越多
    }
 }
</script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值