Vue.js全局事件总线(用于任意组件之间的通信)

饮水思源:https://www.bilibili.com/video/BV1Zy4y1K7SH?p=85&spm_id_from=pageDriver

这是一个便于组件之间通信的办法(适合于任意组件之间!),是由程序员总结而来,并非官方的API

基本原理是借助一个全局对象,进行通信。

①效果演示

大儿子和小儿子是兄弟组件。

②安装全局事件总线

main.js:

import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
  beforeCreate() {
    Vue.prototype.$bus = this; // 这个$bus可以换其它名字
  },
}).$mount('#app')

③使用全局事件总线

<template>
  <div>
    <SonA />
    <SonB />
  </div>
</template>

<script>
import SonA from './components/SonA.vue'
import SonB from './components/SonB.vue'

export default {
  name: 'App',
  components: {
    SonA,
    SonB,
  }
}
</script>

<style>

</style>
App.vue

接听方:

<template>
  <div>
      <h1>大儿子</h1>
      <div>收到来自SonaLine的消息:{{msg}}</div>
  </div>
</template>

<script>

export default {
  name: 'SonA',
  data() {
      return {
          msg: '',
      }
  },
  methods: {
      handleMsgFromSonaLine(msg) {
        this.msg = msg
      },
  },
  mounted() {
    this.$bus.$on('SonaLine', this.handleMsgFromSonaLine);    
  },
  beforeDestroy() {
    this.$bus.$off('SonaLine')
  },
}
</script>

<style scoped>
    div {
        background-color: aqua;
    }
</style>

发送方:

<template>
  <div>
      <h1>小儿子</h1>
      <input v-model="msg">
      <button @click="sendDataToSonA">发数据给大儿子</button>
  </div>
</template>

<script>

export default {
  name: 'SonB',
  data() {
    return {
      msg: '',
    }
  },
  methods: {
    sendDataToSonA() {
      this.$bus.$emit('SonaLine', this.msg)
    } 
  },
}
</script>

<style>
    div {
        background-color: yellow;
        margin-top: 20px;
    }
</style>

最好在beforeDestroy中,解绑当前组件所用到的事件

posted @ 2022-02-09 20:45  xkfx  阅读(174)  评论(0编辑  收藏  举报