Vue-全局事件总线

全局事件总线(GlobalEventBus)

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

在 main.js 中安装全局事件总线

在生命周期函数 beforeCreate 中安装

//创建vm
new Vue({
  render: h => h(App),

  beforeCreate(){
    Vue.prototype.$bus = this  //安装全局事件总线,$bus就是当前应用的vm
  }
  
}).$mount('#app')

发送 $bus.$emit

<template>
  <div>
    <h1>{
   
   { msg }}</h1>
    <button @click="postmsg">向A发送消息</button>
  </div>
</template>

<script>
export default {
  name:'Bb',
  data(){
    return {
      msg:'我是B组件'
    }
  },
  methods:{
    postmsg(){
      this.$bus.$emit('hello',this.msg) //('名称',数据)
    }
  }
  
}
</script>

接收 $bus.$on

<template>
  <div>
    <h1>{
   
   { msg }}</h1>
  </div>
</template>

<script>
export default {
  name:'Aa',
  data(){
    return {
      msg:'我是A组件'
    }
  },
  mounted(){
    this.$bus.$on('hello',(data)=>{
      console.log('A收到了来自B的数据',data);
    })
  },
    //最好在 beforeDestroy 钩子中,用$off去解绑当前组件所用到的事件,否则身上东西太多了
  beforeDestroy(){
    this.$bus.$off('hello')
  }
}
</script>

猜你喜欢

转载自blog.csdn.net/weixin_43472938/article/details/129053516