Vue事件总线 eventBus
如果项目不够大,没有引入 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"><