diff --git a/package.json b/package.json index 4faa283..fc23e7b 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ "axios": "^1.17.0", "cropperjs": "^2.1.1", "element-plus": "^2.14.2", + "mitt": "^3.0.1", "pinia": "^3.0.4", "pinia-plugin-persistedstate": "^4.7.1", "qrcode": "^1.5.4", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ce3db55..333cd7d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -17,6 +17,9 @@ importers: element-plus: specifier: ^2.14.2 version: 2.14.2(vue@3.5.35(typescript@6.0.3)) + mitt: + specifier: ^3.0.1 + version: 3.0.1 pinia: specifier: ^3.0.4 version: 3.0.4(typescript@6.0.3)(vue@3.5.35(typescript@6.0.3)) diff --git a/src/stores/sseBus.ts b/src/stores/sseBus.ts new file mode 100644 index 0000000..cab447b --- /dev/null +++ b/src/stores/sseBus.ts @@ -0,0 +1,40 @@ +// webgame-frontend/src/stores/sseBus.ts +import mitt from 'mitt' +import type { RoomItem } from '@/api/modules/game' + +/** + * SSE 推送事件类型映射 + * + * 每个事件类型对应一个数据类型,类型安全。 + * connected / error 由 useSse 连接管理发出,其余由服务端 SSE 事件映射而来。 + */ +type SseEvents = { + /** SSE 连接成功 */ + connected: void + /** SSE 连接异常 */ + error: { message: string; retryCount: number } + /** 新房间创建 */ + room_created: RoomItem + /** 房间状态更新 */ + room_updated: RoomItem + /** 房间移除 */ + room_removed: { roomId: string } + /** 被踢出房间 */ + kicked: { roomId: string } + /** 所在房间游戏开始 */ + game_started: { roomId: string } + /** 余额变动 */ + balance_chg: { balance: number; delta: number } +} + +/** + * 全局 SSE 事件总线(发布-订阅模式) + * + * 示例: + * ```ts + * import { sseBus } from '@/stores/sseBus' + * const off = sseBus.on('room_updated', (room) => { ... }) + * onUnmounted(off) + * ``` + */ +export const sseBus = mitt()