【Vue3】Mitt

在 Vue3 中,$on$off$once 实例方法被移除,EventBus 无法使用了。那么此时,我们可以使用 Mitt 库(发布订阅模式的设计)。

// 安装 mitt
npm install mitt -S
// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import mitt from 'mitt'
const app = createApp(App)
const Mit = mitt()
declare module 'vue' {
    export interface ComponentCustomProperties {
      $Bus: typeof Mit
    }
}
app.config.globalProperties.$Bus = Mit
app.mount('#app')
<!-- App.vue -->
<template>
  <div>
    <A></A>
    <B></B>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import A from './components/A.vue';
import B from './components/B.vue';
</script>

<style scoped lang="less">

</style>
<!-- A.vue -->
<template>
  <div>
    <h1>我是A组件
    </h1>
    <button @click="emit">emit</button>
    <hr>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance } from 'vue';
const instance = getCurrentInstance();
const emit = () => {
instance?.proxy?.$Bus.emit('a', '我是A组件')
  instance?.proxy?.$Bus.emit('a1', '我是A1组件')
}
</script>

<style scoped></style>

<!-- B.vue -->
<template>
  <div>
    <h1>我是B组件</h1>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance } from 'vue'
const instance = getCurrentInstance()
instance?.proxy?.$Bus.on('a', (str) => {
  console.log(str, '===> B 组件');
})
// '*' 代表监听所有事件触发
instance?.proxy?.$Bus.on('*', (type, str) => {
  console.log(type, str, '===> B 组件');
})
</script>

<style scoped></style>

在这里插入图片描述

还有一些其他方法:

<!-- B.vue -->
<template>
  <div>
    <h1>我是B组件</h1>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance } from 'vue'
const instance = getCurrentInstance()
const Bus = (str: any) => {
  console.log(str, '===> B 组件');
}
instance?.proxy?.$Bus.on('a', Bus)
instance?.proxy?.$Bus.off('a', Bus) // 删除该事件
instance?.proxy?.$Bus.all.clear() // 删除所有事件
</script>

<style scoped></style>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小秀_heo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值