← 返回文章列表

发布订阅模式(EventBus)解耦网络模块和路由模块

在 Vue3 中使用类型安全的发布订阅模式,通过 TS 泛型约束事件名与参数类型,让网络模块只发布标准化事件、路由模块只监听事件,实现网络层与路由层的完全解耦,同时保证类型安全、易于维护。
设计模式 评论 0

核心思路

  1. 事件完全类型化
    事件名必须在 AppEvents 里定义,否则 TS 报错
  2. 参数完全类型化
    发布/监听时,参数自动提示,不会传错
  3. 网络层 ↔ 路由层 完全解耦
    不互相 import、不互相依赖
  4. 可维护性极强
    新增事件只需在 AppEvents 加类型
  5. 符合企业级 TS 规范

1)创建【类型安全的事件总线】(最强版)

src/utils/eventBus.ts

// ==========================================
// 1. 定义所有事件【类型约束】(核心)
// ==========================================
export type AppEvents = {
  // 登录成功:返回用户信息
  'user:loginSuccess': (userInfo: { token: string; userId: string }) => void
  // 登出:无参数
  'user:logout': () => void
  // 登录失败
  'user:loginFail': (msg: string) => void
}

// ==========================================
// 2. 类型安全的 EventBus
// ==========================================
class EventBus {
  private events: Partial<Record<keyof AppEvents, Function[]>> = {}

  // 订阅:只能传定义好的事件,回调类型自动推导
  on<T extends keyof AppEvents>(event: T, callback: AppEvents[T]) {
    if (!this.events[event]) this.events[event] = []
    this.events[event]!.push(callback)
  }

  // 发布:只能传定义好的事件 + 对应参数
  emit<T extends keyof AppEvents>(event: T, ...args: Parameters<AppEvents[T]>) {
    this.events[event]?.forEach(cb => cb(...args))
  }

  // 取消订阅
  off<T extends keyof AppEvents>(event: T, callback: AppEvents[T]) {
    if (!this.events[event]) return
    this.events[event] = this.events[event]!.filter(cb => cb !== callback)
  }
}

export const eventBus = new EventBus()

// =============================================
// 3. 组合式API:自动取消订阅(核心!解决内存泄漏)
// =============================================
import { onUnmounted } from 'vue'

export function useEventBus<T extends keyof AppEvents>(
  event: T,
  callback: AppEvents[T]
) {
  eventBus.on(event, callback)

  onUnmounted(() => {
    eventBus.off(event, callback)
  })
}


2)网络模块(完全类型提示)

src/api/user.ts

import axios from 'axios'
import { eventBus } from '@/utils/eventBus'

// 登录请求
export async function loginApi(username: string, password: string) {
  try {
    const { data } = await axios.post('/api/login', { username, password })

    // ✅ TS 自动提示事件名 + 参数类型
    eventBus.emit('user:loginSuccess', {
      token: data.token,
      userId: data.userId
    })
  } catch (err: any) {
    eventBus.emit('user:loginFail', err.message || '登录失败')
  }
}

// 登出请求
export async function logoutApi() {
  await axios.post('/api/logout')
  eventBus.emit('user:logout')
}

3)路由模块(监听也有类型)

src/router/index.ts

import { createRouter, createWebHistory } from 'vue-router'
import { eventBus } from '@/utils/eventBus'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/login', component: () => import('@/views/Login.vue') },
    { path: '/home', component: () => import('@/views/Home.vue') }
  ]
})

// ==========================================
// 👇 监听:参数自动推导类型
// ==========================================
eventBus.on('user:loginSuccess', (userInfo) => {
  // userInfo 自动类型:{ token:string; userId:string }
  router.push('/home')
})

eventBus.on('user:logout', () => {
  router.push('/login')
})

export default router

4)页面使用(完全干净、无耦合)(自动取消订阅)

Login.vue

<script setup lang="ts">
import { loginApi } from '@/api/user'
import { useEventBus } from '@/utils/eventBus'

// 登录失败提示(组件销毁时自动取消订阅)
useEventBus('user:loginFail', (msg) => {
  console.log('失败:', msg)
  ElMessage.error(msg)
})

const handleLogin = async () => {
  await loginApi('admin', '123456')
}
</script>

<template>
  <button @click="handleLogin">登录</button>
</template>

Home.vue

<script setup lang="ts">
import { logoutApi } from '@/api/user'

const handleLogout = async () => {
  await logoutApi()
}
</script>

<template>
  <button @click="handleLogout">退出登录</button>
</template>
评论: