Vue - Global Event Bus

Global Event Bus (GlobalEventBus)

A way of communicating between components, suitable for任意组件间通信

Install the global event bus in main.js

Install in the lifecycle function beforeCreate

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

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

send$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>

take over$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>

Guess you like

Origin blog.csdn.net/weixin_43472938/article/details/129053516