Vue 3 中使用 Mitt 事件總線方案詳解
Vue3中使用Mitt事件總線實現(xiàn)組件通信。
Mitt是一個輕量級的事件庫,可作為全局事件總線替代方案。
文章介紹了基本使用方法:創(chuàng)建事件總線實例、定義事件類型、在組件中發(fā)射和監(jiān)聽事件,并強(qiáng)調(diào)組件卸載時需取消監(jiān)聽以避免內(nèi)存泄漏。
還展示了高級用法:工廠模式創(chuàng)建多總線、封裝Vue插件、CompositionAPI封裝Hook。
最后對比了Mitt與Vue原生通信方式的差異,建議謹(jǐn)慎使用事件總線,優(yōu)先考慮props/emit或provide/inject等更明確的通信方式。
Vue 3 中使用 Mitt 事件總線
Mitt 是一個輕量級的事件發(fā)射/監(jiān)聽庫,在 Vue 3 中可以作為全局事件總線的替代方案。
安裝
npm install mitt # 或 yarn add mitt # 或 pnpm add mitt
基本使用
1.創(chuàng)建事件總線實例
方式一:創(chuàng)建全局事件總線
// src/utils/eventBus.ts
import mitt from 'mitt'
type Events = {
// 定義事件類型
'user-login': { userId: string; username: string }
'user-logout': void
'notification': string
'update-count': number
// 使用通配符監(jiān)聽所有事件
'*': { type: string; payload?: any }
}
const eventBus = mitt<Events>()
export default eventBus方式二:在 Composition API 中使用
vue
<!-- ComponentA.vue -->
<script setup lang="ts">
import { onUnmounted } from 'vue'
import eventBus from '@/utils/eventBus'
// 發(fā)射事件
const emitLogin = () => {
eventBus.emit('user-login', {
userId: '123',
username: '張三'
})
}
// 監(jiān)聽事件
eventBus.on('notification', (message) => {
console.log('收到通知:', message)
})
// 監(jiān)聽所有事件
eventBus.on('*', (type, payload) => {
console.log(`事件類型: ${type}`, payload)
})
// 組件卸載時取消監(jiān)聽
onUnmounted(() => {
eventBus.off('notification')
// 或者取消所有監(jiān)聽
// eventBus.all.clear()
})
</script>2.在多個組件中使用
vue
<!-- Header.vue -->
<script setup lang="ts">
import eventBus from '@/utils/eventBus'
const logout = () => {
eventBus.emit('user-logout')
}
const sendNotification = () => {
eventBus.emit('notification', '新消息!')
}
</script>vue
<!-- Sidebar.vue -->
<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import eventBus from '@/utils/eventBus'
const notification = ref('')
const handleNotification = (message: string) => {
notification.value = message
setTimeout(() => notification.value = '', 3000)
}
onMounted(() => {
eventBus.on('notification', handleNotification)
})
onUnmounted(() => {
eventBus.off('notification', handleNotification)
})
</script>高級用法
1.使用工廠模式創(chuàng)建多個事件總線
// src/utils/eventBusFactory.ts
import mitt from 'mitt'
export function createEventBus<T>() {
return mitt<T>()
}
// 創(chuàng)建不同的事件總線
export const uiEventBus = createEventBus<{
'modal-open': { id: string }
'modal-close': string
}>()
export const dataEventBus = createEventBus<{
'data-loaded': any[]
'data-error': Error
}>()2.封裝為 Vue 插件
// src/plugins/eventBus.ts
import { type App } from 'vue'
import mitt, { type Emitter } from 'mitt'
// 事件類型定義
type Events = {
[key: string]: any
}
// 創(chuàng)建全局事件總線
const eventBus: Emitter<Events> = mitt<Events>()
export const EventBusPlugin = {
install(app: App) {
// 全局屬性
app.config.globalProperties.$eventBus = eventBus
// 提供/注入
app.provide('eventBus', eventBus)
}
}
// 在 Composition API 中使用的 Hook
export function useEventBus() {
const eventBus = inject<Emitter<Events>>('eventBus')
if (!eventBus) {
throw new Error('Event bus not provided')
}
return eventBus
}
export default eventBusmain.ts
// main.ts
import { createApp } from 'vue'
import { EventBusPlugin } from '@/plugins/eventBus'
import App from './App.vue'
const app = createApp(App)
app.use(EventBusPlugin)
app.mount('#app')3.在 Composition API 中封裝 Hook
typescript
// src/composables/useEventBus.ts
import { onUnmounted } from 'vue'
import eventBus, { type Handler } from '@/utils/eventBus'
export function useEventBus() {
const listeners: Array<[string, Handler]> = []
const emit = <T = any>(event: string, payload?: T) => {
eventBus.emit(event, payload)
}
const on = <T = any>(event: string, handler: (payload: T) => void) => {
eventBus.on(event, handler as Handler)
listeners.push([event, handler as Handler])
}
const off = <T = any>(event: string, handler: (payload: T) => void) => {
eventBus.off(event, handler as Handler)
const index = listeners.findIndex(
([e, h]) => e === event && h === handler
)
if (index > -1) {
listeners.splice(index, 1)
}
}
const once = <T = any>(event: string, handler: (payload: T) => void) => {
const onceHandler = (payload: T) => {
handler(payload)
off(event, onceHandler)
}
on(event, onceHandler)
}
// 自動清理監(jiān)聽器
onUnmounted(() => {
listeners.forEach(([event, handler]) => {
eventBus.off(event, handler)
})
listeners.length = 0
})
return {
emit,
on,
off,
once
}
}vue
<!-- 使用封裝的 Hook -->
<script setup lang="ts">
import { useEventBus } from '@/composables/useEventBus'
const { emit, on, once } = useEventBus()
// 發(fā)送事件
const sendEvent = () => {
emit('custom-event', { data: 'test' })
}
// 監(jiān)聽事件
on('custom-event', (payload) => {
console.log('收到事件:', payload)
})
// 只監(jiān)聽一次
once('one-time-event', (payload) => {
console.log('只會觸發(fā)一次:', payload)
})
</script>與 Vue 原生方法的比較
| 特性 | Mitt | Vue 3 的 emit/props | Provide/Inject |
|---|---|---|---|
| 通信范圍 | 任意組件間 | 父子組件間 | 祖先-后代組件間 |
| 類型支持 | TypeScript 友好 | TypeScript 友好 | TypeScript 友好 |
| 耦合度 | 低 | 高 | 中 |
| 適用場景 | 全局事件、兄弟組件 | 父子組件 | 層級深的組件 |
最佳實踐
類型安全
// 正確定義事件類型
type Events = {
'user-updated': User
'cart-changed': CartItem[]
}及時清理
// 組件卸載時取消監(jiān)聽
onUnmounted(() => {
eventBus.off('event-name', handler)
})- 避免過度使用
- 優(yōu)先使用 props/emit 進(jìn)行父子組件通信
- 優(yōu)先使用 provide/inject 進(jìn)行層級通信
- 只在需要跨多級/兄弟組件通信時使用事件總線
- 錯誤處理
const { emit, on } = useEventBus()
on('error-event', (error) => {
// 統(tǒng)一錯誤處理
console.error('事件錯誤:', error)
})注意事項
- 內(nèi)存泄漏:務(wù)必在組件卸載時取消事件監(jiān)聽
- 調(diào)試?yán)щy:事件總線可能導(dǎo)致數(shù)據(jù)流不清晰
- 替代方案:對于復(fù)雜應(yīng)用,考慮使用 Pinia 進(jìn)行狀態(tài)管理
Mitt 在 Vue 3 中是一個簡單有效的跨組件通信方案,但應(yīng)謹(jǐn)慎使用,避免濫用導(dǎo)致代碼難以維護(hù)。
到此這篇關(guān)于Vue 3 中使用 Mitt 事件總線的文章就介紹到這了,更多相關(guān)vue Mitt 事件總線內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用element-ui設(shè)置table組件寬度(width)為百分比
這篇文章主要介紹了使用element-ui設(shè)置table組件寬度(width)為百分比方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04
深入探討Vue計算屬性與監(jiān)聽器的區(qū)別和用途
在Vue的開發(fā)中,計算屬性(Computed Properties)和監(jiān)聽器(Watchers)是兩種非常重要的概念,它們都用于響應(yīng)式地處理數(shù)據(jù)變化,本文將帶你深入了解計算屬性和監(jiān)聽器的區(qū)別,以及在何時使用它們,感興趣的朋友可以參考下2023-09-09
詳解基于vue-cli3.0如何構(gòu)建功能完善的前端架子
這篇文章主要介紹了詳解基于vue-cli3.0如何構(gòu)建功能完善的前端架子,本文整合出具備基礎(chǔ)功能的前端架子,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-10-10
element-ui el-dialog嵌套table組件,ref問題及解決
這篇文章主要介紹了element-ui el-dialog嵌套table組件,ref問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02
vue?watch監(jiān)聽觸發(fā)優(yōu)化搜索框的性能防抖節(jié)流的比較
這篇文章主要為大家介紹了vue?watch監(jiān)聽觸發(fā)優(yōu)化搜索框的性能防抖節(jié)流的比較,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10

