1.概念
EventBus是消息傳遞的一種方式,基於一個消息中心,訂閱和發布消息的模式,稱為發布訂閱者模式。
- on('name', fn)訂閱消息,name:訂閱的消息名稱, fn: 訂閱的消息
- emit('name', args)發布消息, name:發布的消息名稱 , args:發布的消息
2.實現
3.使用

注:只不過在vue中已經替我們實現好了$emit
,$on
這些方法,所以直接用的時候去 new Vue()
就可以了.
4.實例
定義event-bus.js文件
import Vue from 'vue'
const eventBus= new Vue()
export default eventBus
使用頁面:
import eventBus from '@/system/lib/event-bus' //引入
event-bus.js文件
//創建的時候調用 getList這個自定義方法
created() {
eventBus.$on('getlist', this.getErTongYFJZJLList)
// 監聽接收消息
},
//組件銷毀時 移除監聽事件
beforeDestroy(){
eventBus.$off('getlist') //移除監聽事件
},
// 發送消息
eventBus.$emit('getlist', this.jianKangDAID)
調用父頁面方法:this.$parent.pageInit()
調用子組件方法: this.$refs.YuFangJZXX.open()
<form-jiezhongxx :jianKangDAID="jianKangDAID" :id="id" ref="YuFangJZXX"></form-jiezhongxx>
父頁面給子頁面傳值:

子頁面給父頁面傳值:
父:父組件,v-on接收 @是v-on的簡寫。
<zidianxz ref="ZiDianXZ"
@yinru="yinruHandle"></zidianxz>
//引入模板
yinruHandle(moBanMC, list) {
if (
moBanMC == 'jieZhongJJ' ||
moBanMC == 'yiChangFYS' ||
moBanMC == 'chuanRanBS'
) {
this.formModel[moBanMC][this.currentIndex].xianShiNR =
list[0].neiRong + (list[0].beiZhu ? ':' + list[0].beiZhu : '')
this.formModel[moBanMC][this.currentIndex].neiRong = list[0].neiRong
this.formModel[moBanMC][this.currentIndex].beiZhu = list[0].beiZhu
} else {
this.$set(this.formModel, moBanMC, list.join(''))
}
},
子:1.子組件,this.$emit
<el-button type="primary" @click="yinRu">引入</el-button>
yinRu() {
for (let i of this.data) {
if (i.isSet) {
this.$message({
message: '請先保存所有內容',
type: 'warning'
})
return
}
}
let result = []
if (this.more) {
for (let i of this.multipleSelection) {
result.push(i)
}
} else {
for (let i of this.multipleSelection) {
result.push(i.neiRong)
}
}
this.updateData = []
this.$emit('yinru', this.moBanMC, result)
this.dialogVisible = false
},