vue中使用eventBus

vue2

方法一:

//eventBus.js
import Vue from 'vue';

export const eventBus = new Vue();


//$emit操作页:pageA.js

html: 

 <button @click="countPlus">点击count++</button>

当前的count:{{myCount}}

js:

import { eventBus } from "@/common/eventBus";

methods: {

    countPlus() {

      this.myCount++;

//使用事件派发,触发myCountPlus事件,并将this.myCount作为参数传出去(在pageB中便可以接收到这个参数,以此来实现点击按钮两个组件的值一致)  

    eventBus.$emit("myCountPlus", this.myCount);

    }

  },


//$on接收页:pageB.js

html:

<p>当前的myCount值为{{myCount}}</p>

js:

import { eventBus } from "@/common/eventBus";

mounted() {

    //通过事件总线监听myCountPlus事件,事件触发后执行回到函数,在本页面更新myCount的值,保持和Count组件中穿过来的值一致,v代表从Count组件中传过来的值

    eventBus.$on("myCountPlus", v => {

      this.myCount = v;

    });

  },


方法二://全局

//再main.js中创建一个事件总线,就是创建一个新的Vue对象

const eventBus = new Vue();

Vue.prototype.$eventBus = eventBus; //在vue的原型对象上创建了一个事件总线

//$emit操作页

methods: {

    countPlus() {

            //业务逻辑...

        this.$eventBus.$emit("fnName", data);

    }

}

//$on接收页

mounted() {

this.$EventBus.$on("fnName", (data) => {

//业务逻辑...

    });

}


vue3 //支持eventBus,$on、$off 和 $once 实例方法被删除

方法一:自己写一个bus

第一步:eventBus.js

// 为保持和vue2版本中使用bus一致,emit,on,off前面都加了$

class Bus {

    list: { [key: string]: Array<Function> };

    constructor() {

        // 收集订阅信息,调度中心

        this.list = {};

    }

    // 订阅

    $on(name: string, fn: Function) {

        this.list[name] = this.list[name] || [];

        this.list[name].push(fn);

    }

    // 发布

    $emit(name: string, data?: any) {

        if (this.list[name]) {

            this.list[name].forEach((fn: Function) => {

            fn(data);

      });

    }

    }

    // 取消订阅

    $off(name: string) {

        if (this.list[name]) {

            delete this.list[name];

        }

    }

}

export default Bus;


第二步:

//bus.js

import Bus from './eventBus.ts';

const bus = new Bus();

export default bus;


第三步:

使用同vu2的方法一

import bus from "/@/common/bus.js";

引用,使用.....


参考:https://blog.csdn.net/weixin_35958891/article/details/110441771

方法二使用第三方库,比如 mitt

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容