全局时间总线

geb01

一种组件间通讯的方式,适用于任意组件间通信

1、安装全局事件总线

1
2
3
4
5
6
7
new Vue({
......
beforeCreate() {
Vue.prototype.$bus = this; //安装全局事件总线,$bus就是当前应用的vm
},
......
})
  1. 使用事件总线:

    (1)接收数据:A组件想要接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    methods: {
    demo(data) {
    ......
    },
    },
    mounted() {
    //方法一
    this.$bus.$on("hello", this.demo);
    //方法二
    //this.$bus.$on("hello", (data) => {......});
    },
    beforeDestroy() {
    this.$bus.$off("hello",);
    },

    (2)提供数据 this.$bus.$emit('xxxx',数据)

  2. 最好在beforeDestory钩子中,用$off去解绑当前组件所到用的事件。


全局时间总线
http://vityabour.github.io/2023/10/23/全局事件总线/
作者
Vity Abour
发布于
2023年10月23日
许可协议