在 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>