Vue事件总线 eventBus

落爺英雄遲暮 提交于 2019-11-30 02:20:19

如果项目不够大,没有引入 Vuex 的情况下,组件还不是父子组件的关系,也不适合使用 params、query 等路由传参方式进行传参的话,那组件之间应该如何通信呢?

公共事件总线 eventBus 的 实质 就是创建一个 vue 实例,通过一个空的 vue 实例作为桥梁实现 vue 组件间的通信。它是实现非父子组件通信的一种解决方案。

引入方式

方式一:

新建一个文件,比如叫 eventBus.js 然后放到项目根目录,

文件总共也就两行代码:

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

然后你的哪些组件需要通信,在那些组件中 import 导入即可。

方式二:

直接在 main.js 中:

Vue.prototype.eventBus = new Vue()

方式三:

还是在 main.js 中:

const app = new Vue({
    el: "#app",
    router,
    data: {
        eventBus: new Vue()
    },
    render: h => h(App)
});

需要注意的是:使用这种方式的时,调用是这样调用的:

this.$root.eventBus

使用方式

使用 $emit 发送数据:

<template>
  <div>
    <button @click="send"></button>
  </div>
</template>

<script>
export default {
  methods: {
    send() {
      this.$root.eventBus.$emit("some_data", 2333);
    }
  }
};
</script>

使用 $on 接收数据:

<template>
  <div></div>
</template>

<script>
export default {
  data() {
    return {
      the_data: 0
    };
  },
  mounted() {
    this.$root.eventBus.$on("some_data", msg => {
      this.the_data = msg;
    });
  }
};
</script>

以上,就是 eventBus 的基本用法了,不过 eventBus 坑很多

其中一个就是 $emit 和 $on 不会随着页面的销毁而销毁,所以我们需要每次都手动销毁:

  destroyed() {
    this.$root.eventBus.$off("some_data");
  }

注意:两个页面都要使用 $off 消除事件;

eventBus 还存在着传递的数据拿不到的坑和数据多次发送的坑,请大家看我的下一篇博客《Vue eventBus 踩坑记录》🌸✨🌼🌻🌺

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!