vue組件通信方式之兄弟組件通信eventBus

eventBus單獨(dú)的事件中心,用來(lái)管理組件之間的通信。

由于 Vue 實(shí)例實(shí)現(xiàn)了一個(gè)事件分發(fā)接口,你可以通過(guò)實(shí)例化一個(gè)空的 Vue 實(shí)例來(lái)實(shí)現(xiàn)這個(gè)目的。
然后在組件中,可以使用$emit, $on, $off 分別來(lái)分發(fā)、監(jiān)聽(tīng)、取消監(jiān)聽(tīng)事件。
需求:點(diǎn)擊左側(cè)聯(lián)系人,改變右側(cè)聊天記錄框頭部聯(lián)系人信息,并獲取對(duì)應(yīng)的聊天記錄。
左側(cè)聯(lián)系人列表left.vue和右側(cè)聊天記錄框right.vue系兄弟組件。

1.在utils文件夾里創(chuàng)建一個(gè)bus.js文件,里面寫上如下代碼:

import Vue from 'vue'
export default new Vue()

2.引入utils中的bus文件import eventBus from '@/utils/bus'。
在left.vue中將需要分發(fā)的數(shù)據(jù)item命名為chatterData,通過(guò)eventBus.$emit('chatterData', item)方式分發(fā)。

<template>
  <div class="chatLeft" :style="leftStyle">   
    <div class="list" v-loading="loading">
      <div v-for="(item, index) in this.showData" :key="index" @click="selectCustomer(index, item)" :class="index === n ? 'actived' : ''">
        <List :details="item" :type="false"/>
      </div>
    </div>
  </div>
</template>
methods: {
    selectCustomer(index, item) {
      eventBus.$emit('chatterData', item)
    }
}

3.引入utils中的bus文件import eventBus from '@/utils/bus'。
在right.vue中通過(guò)eventBus.$on('chatterData', (val) => {})方式進(jìn)行接收。

created(){
    eventBus.$on('chatterData', (val) => {
      this.customerInfo = val
      this.listParams.externalUserid = val.externalUserid
    })
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容