美文网首页
vue中使用eventBus

vue中使用eventBus

作者: 我是MN_8888 | 来源:发表于2021-07-14 12:17 被阅读0次

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

相关文章

网友评论

      本文标题:vue中使用eventBus

      本文链接:https://www.haomeiwen.com/subject/kvkypltx.html