全局事件总线

PPG007 ... 2021-12-25 Less than 1 minute

# 全局事件总线

全局事件总线:

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

# 设置全局总线

main.js 中通过为 Vue 原型对象添加属性实现创建总线,且该总线能够访问所有的 Vue 对象方法:

new Vue({
  render: h => h(App),
  beforeCreate() {
    Vue.prototype.$bus=this;
  }
}).$mount('#app')
1
2
3
4
5
6

# 使用事件总线

# 接收数据

A 组件要接收数据,A 组件中在总线上创建自定义事件:

mounted() {
    this.$bus.$on('getInfo',(student,school)=>{
        if (school){
            this.school={'name':school.name,'address':school.address};
        }
        if (student){
            this.student={'name':student.name,'age':student.age};
        }
    })
}
1
2
3
4
5
6
7
8
9
10

# 发送数据

B 组件要发送数据,B 组件中调用 $emit() 方法调用其他组件创建的自定义事件并传递数据:

methods:{
    showAll(){
        this.$bus.$emit('getInfo',{'name':this.name,'age':this.age});
    }
}
1
2
3
4
5

Tips

最好在 beforeDestroy() 中解绑自己创建的事件:

  beforeDestroy() {
    this.$bus.$off('getInfo');
  }
1
2
3
Last update: December 25, 2021 14:08
Contributors: PPG007