vue中eventBus的实现原理


1.概念
EventBus是消息传递的一种方式,基于一个消息中心,订阅和发布消息的模式,称为发布订阅者模式。

  1. on('name', fn)订阅消息,name:订阅的消息名称, fn: 订阅的消息
  2. 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
    },

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM