vue3中如何实现事件总线eventBus

25 篇文章 1 订阅

使用插件

由于vue3中 “$ on”,$ off 和 $ once 实例方法已被移除,组件实例不再实现事件触发接口 所以我们可以使用官方推荐的这个第三方库实现同样的效果
mitt https://github.com/developit/mitt

安装

pnpm install mitt -S

挂载全局写法

main.ts 初始化
全局总线,vue 入口文件 main.js 中挂载全局属性

import './assets/main.css'

import { createApp } from 'vue'
import { createPinia } from 'pinia'

import App from './App.vue'
import router from './router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
// 引入animate动画
import 'animate.css';
//挂载事务总线
import mitt from 'mitt'
const app = createApp(App)
const miTT = mitt()
//TypeScript注册
// 由于必须要拓展ComponentCustomProperties类型才能获得类型提示
declare module "vue" {
  export interface ComponentCustomProperties {
      $bus: typeof miTT
  }
}

app.config.globalProperties.$bus = miTT

app.use(createPinia())
app.use(router)
app.use(ElementPlus)
app.mount('#app')

父组件

<template>
  <A></A>
  <B></B>
</template>

<script setup lang="ts">
import A from './components/A.vue'
import B from './components/B.vue'
</script>

<style scoped>

</style>

组件A

<template>
  <div style="margin-right: 30px;">
    <h1>派发组件</h1>
     <button @click="emitIndex">派发事件</button>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance } from 'vue'
// vue实例
const vm = getCurrentInstance();
 const emitIndex = () => {
  // self.console.log(123,vm)
  vm?.proxy?.$bus.emit('on-click', 1)
 }
</script>

<style scoped>

</style>

组件B

<template>
  <div>
   <h1>接收组件</h1>
   <div>接收的值{{ bData }}</div>
  </div>
 </template>
 
 <script setup lang="ts">
 import { getCurrentInstance,ref } from 'vue'
  const vm = getCurrentInstance()
  let bData = ref<Number>(0)
  vm?.proxy?.$bus.on('on-click', (num) => {
      bData.value += num
      console.log(num,'===========>B')
  })
 </script>
 
 <style scoped>
 
 </style>
 

效果如下

点击 按钮 b组件中的数值增加

在这里插入图片描述
监听所有事件( on(“*”) )

vm?.proxy?.$bus.on('*', (num) => {
      bData.value += num
      console.log(num,'===========>B')
  })

移除监听事件(off)

vm?.proxy?.$Bus.on('on-click',Fn)//listen
vm?.proxy?.$Bus.off('on-click',Fn)//unListen

清空所有监听(clear)

vm?.proxy?.$Bus.all.clear() 
  • 14
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值