vue3使用事件总线传值

文章介绍了Vue中如何使用$bus对象进行事件监听(on)和触发(emit),特别是在组件实例中通过`getCurrentInstance()`获取$bus并实现代理方法,强调了bus.on无需显式调用方法的优点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

bus.on 接收

    import { computed, defineComponent, getCurrentInstance } from 'vue' 
    
    const instance = getCurrentInstance()
    if(instance){
      const bus = instance?.appContext.config.globalProperties.$bus
      // 一个神奇的事情,bus.on自己有触发器,不需要写在方法里 用方法名()的方式 ,就可以调用=======================这也是小重点====================
      //=========只要bus.emit发布了,bus.on就能接收到;所以bus.on可以不用写在方法里,然后用方法名()的方式调用;直接就可以执行====================
      bus.on('activeMenuPath', (data) => {
        for(let i = 0;i < navData.value.length ; i++){
          if(data == navData.value[i].path){
            selectPath.value = data;
            break
          }else{
            selectPath.value = ''
          }
        }
      })
    }

 bus.emit 发布

import { computed, defineComponent, getCurrentInstance } from 'vue'

const instance = getCurrentInstance()
const activeMenu = computed(() => {
      if(instance){
          const bus = instance.appContext.config.globalProperties.$bus
          bus.emit('activeMenuPath',route.path)
       }
       if(route.meta.activeMenu) return route.meta.activeMenu
       return route.path
})
       

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值