baozhengrui

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

vue之间的传值问题---6eventbus 可以实现兄弟组件通信

1.传递数据的组件:通过eventbus中的方法$emit来发布自定义事件,并且传递数据
2.接收数据的组件: 通过eventbus中的方法$on来订阅事件,并通过回调函数接收数据

// 手写发布订阅模式
class EventBus {
  // 记录事件和回调
  clientList = {
    send: [() => {}, () => {}],
  }
  // 订阅事件,参数event事件名,callback 回调
  $on = function (event, callback) {
    // 将事件和函数记录
    // 如果事件记录过,那就将回调push
    if (this.clientList[event]) {
      this.clientList[event].push(callback)
    } else {
      this.clientList[event] = [callback]
    }
  }
 
  $emit = function (event, val) {
    if (!this.clientList[event]) {
      throw new Error(event + ' is not a event')
    }
    this.clientList[event].forEach((cb) => {
      cb(val)
    })
  }
}
 
const eventBus = new EventBus()
 
// 订阅事件
eventBus.$on('send', (val) => {
  console.log('send订阅' + val)  获取
})
 
eventBus.$emit('send', 1)  传值

使用案例:

// 公公bus.js
//bus.js
import Vue from 'vue'
export default new Vue()

组件A(传值的页面)
<template>
  <div>
    A组件:
    <span>{{elementValue}}</span>
    <input type="button" value="点击触发" @click="elementByValue">
  </div>
</template>
<script>
  // 引入公共的bug,来做为中间传达的工具
  import Bus from './bus.js'
  export default {
    data () {
      return {
        elementValue: 4
      }
    },
    methods: {
      elementByValue () {
        Bus.$emit('val', this.elementValue)
      }
    }
  }
</script>

组件B (接收值的页面)

<template>
  <div>
    B组件:
    <input type="button" value="点击触发" @click="getData">
    <span>{{name}}</span>
  </div>
</template>
<script>
  import Bus from './bus.js'
  export default {
    data () {
      return {
        name: 0
      }
    },
    mounted () {
      // 用$on事件来接收参数
      Bus.$on('val', elementValue => {
        console.log(elementValue)
        vm.name = elementValue
      })
    },
    methods: {
      getData () {
        this.name++
      }
    }
  }
</script>






posted on   芮艺  阅读(46)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示