JS VUE 全局的事件总线

本文介绍了在Vue项目中如何实现组件间的通信,通过创建全局事件总线来简化跨组件的数据传递过程。提供了两种实现方式:一种是基于Vue实例的事件总线;另一种是纯JS实现的事件总线。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

                                                  JS  VUE   全局的事件总线

1: 在  VUE 中各个组件相互调用,可以使用 基于 VUE  的事件总线

第一种写法:

独立的  .js 文件 比如 eventbus.js, 然后在别的 vue 或者 js 中引用

import Vue from 'vue'
export const EventBus = new Vue()

第二种写法:

以直接在项目中的 main.js 初始化 EventBus

Vue.prototype.$EventBus = new Vue()

具体使用: 分监听 和 调用 两个步骤:可以在 相同的 .vue 也可在不同的 .vue

监听:
this.EventBus.$on("decreased", ({num,deg}) => {
     // Do something
});

触发:
this.EventBus.$emit("incremented", {
     num:this.num,
     deg:this.deg
});

 

2: 在  JS 中各个组件相互调用,可以使用 基于 JS  的事件总线。 由于 使用  Vue.prototype.$EventBus 的方式 具有一定的局限性 比方说 在  .js 中 就不太好 使用 .vue 所以这里  介绍另一种方式

源码: EventBus.js

(function (exporter) {
    function isFunc(fn) { return typeof fn === "function" }
    function str(s) {
        if (s == null) {
            return null;
        }
        s = s.replace(/^\s+|\s+$/g, "");
        return s.length > 0 ? s.toLowerCase() : null;
    }
 
    function handler() {
        var fns = [];
        var datas = [];
        this.add = function (fn, data) {
            fns.push(fn);
            datas.push(data);
        }
        this.remove = function (fn) {
            var i = fns.indexOf(fn);
            if (i >= 0) {
                fns.splice(i, 1);
                datas.splice(i, 1);
            }
        }
        this.invoke = function (sender, data) {
            fns.forEach((fn, i) => {
                try {
                    fn(sender, data, datas[i])
                } catch (error) {
                    console.error(error);
                }
            });
        }
    }
 
    function eventBus() {
        var handers = {}
        this.on = function (eventName, fnOrData, fn) {
            eventName = str(eventName);
            if (eventName == null) {
                throw new Error("事件名无效");
            }
            if (!isFunc(fn)) {
                var temp = fn;
                fn = fnOrData;
                fnOrData = temp;
            }
            if (!isFunc(fn)) {
                throw new Error("必须提供事件函数");
            }
            var handle = handers[eventName];
            if (handle == null) {
                handle = new handler();
                handers[eventName] = handle;
            }
            handle.add(fn, fnOrData);
        }
        this.off = function (eventName, fn) {
            eventName = str(eventName);
            if (eventName == null) {
                return;
            }
            var handle = handers[eventName];
            if (handle != null) {
                if (fn == null) {
                    delete handers[eventName];
                } else {
                    handle.remove(fn);
                }
            }
        }
        this.fire = this.emit = this.trigger =
            function (eventName, sender, data) {
                eventName = str(eventName);
                if (eventName == null) {
                    return;
                }
                var handle = handers[eventName];
                if (handle != null) {
                    handle.invoke(sender, data);
                }
            }
        var bus = this;
        this.bindTo = function(obj){
            if(obj == null){
                throw new Error("obj is null");
            }
            for (const key in bus) {
                if (bus.hasOwnProperty(key) && key !== "bindTo") {
                    obj[key] = bus[key];
                }
            }
        }
    }
    var instance = new eventBus();
    instance.bindTo(eventBus);
    exporter(eventBus);
})(c => window.eventBus = c)

你可以在   main.js  引入一下 就可以全局使用了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nicepainkiller

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值