Bus总线

... 2025-7-10 Code 大约 2 分钟

EventBus(事件总线):解决兄弟组件通信的问题,当然也可以选择 vuex

注意点

  • 注册的总线事件要在组件销毁时卸载,否则会多次挂载,造成触发一次但多个响应的情况

  • 事件订阅是通过 $eventBus 对象完成的 与组件无关,如果不移除事件监听 并且会造成内存泄漏,需要在子组件销毁后进行取消订阅事件

  • $on 先执行 在执行 $emit 触发事件


  • 任何组件都可以在事件总线中发布事件 this.$bus.$emit('xxx','传参')

  • 任何组件都可以在事件总线中监听事件 this.$bus.$on('xxx',(入参)=>{ 对形参进行操作 })

  • main.js 注册空的 Vue 对象, 只负责$on注册事件, $emit触发事件, 一定要确保 ​$on先执行

  • $off 的格式:

    • $off() 会取消所有的事件订阅

    • $off('事件名') 会取消指定事件名的

    • $off('事件名', 回调) 会取消指定事件名的,指定回调

# 使用方法

  • 方法一
// bus.js
import Vue from 'vue'
const bus = new Vue()
export default bus
1
2
3
4
// main.vue
<template>
  <div>
    <child1></child1>
    <child2></child2>
  </div>
</template>
<script>
export default {
  name: 'TestBaiDu',
  components: {
    child1: () => import('@/components/child1'),
    child2: () => import('@/components/child2'),
  },
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// child1.vue
<template>
  <div>
    这是一个A组件
    <el-button type="primary" @click="clickEve">点击</el-button>
  </div>
</template>

<script>
import bus from './bus'
export default {
  data() {
    return {}
  },
  methods: {
    clickEve() {
      bus.$emit('getMessage', 'qqqq')
    },
  },
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// child2.vue
<template>
  <div>这是一个B组件</div>
</template>

<script>
import bus from './bus'
export default {
  data() {
    return {}
  },
  methods: {
    showMsg(msg) {
      console.log('msg', msg)
    },
  },
  created() {
    bus.$on('getMessage', this.showMsg)
  },
  beforDestory() {
    this.$off('getMessage', this.showMsg)
  },
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

  • 方法二

把 bus 定义在 vue 的 prototype 上,在全局都可以使用

main.js 中加入如下代码

const bus = new Vue()
Vue.prototype.$bus = bus
1
2

这样我们就不需要再自己写 bus.js 引入了,就可以直接再组建中使用

this.$bus.on()this.$bus.$emit()this.$bus.$off()


  • 方法三

使用插件 vue-bus

安装 npm install vue-bus --save

main.js 中引入

import VueBus from 'vue-bus' //中央事件总线
Vue.use(VueBus)
1
2

这样我们就不需要再自己写 bus.js 引入了,就可以直接再组建中使用

this.$bus.on()this.$bus.$emit()this.$bus.$off()

上次编辑于: 2025年7月10日 04:01
贡献者: HugStars