feat: App.vue 集成 SSE 连接管理,Lobby.vue 订阅实时房间事件

This commit is contained in:
2026-06-22 13:47:15 +08:00
parent dfc54edd83
commit f8db0ea4d6
2 changed files with 43 additions and 1 deletions

View File

@@ -5,7 +5,26 @@
</template>
<script setup lang="ts">
import { watch } from 'vue'
import { RouterView } from 'vue-router'
import { ElConfigProvider } from 'element-plus'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { useSse } from '@/common/hooks/useSse'
import { useAccountStore } from '@/stores/modules/account'
const accountStore = useAccountStore()
const { connect, disconnect } = useSse()
// 登录后建立 SSE 连接,登出时断开
watch(
() => accountStore.accessToken,
(token) => {
if (token) {
connect()
} else {
disconnect()
}
},
{ immediate: true }
)
</script>

View File

@@ -44,13 +44,14 @@
</template>
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import TableCard from './TableCard.vue'
import CreateRoomDialog from './CreateRoomDialog.vue'
import type { RoomItem } from '@/api/modules/game'
import { useBaseLayoutStore } from '@/stores'
import { storeToRefs } from 'pinia'
import { getRoomList } from '@/api/modules/game'
import { sseBus } from '@/stores/sseBus'
/** 状态筛选选项 */
const statusFilters = [
@@ -88,6 +89,28 @@ watch(activeGameId, () => {
/** 首次加载 */
fetchRoomList()
// ===== SSE 实时事件订阅 =====
onMounted(() => {
const offs = [
// 新房间创建 → 添加到列表头部
sseBus.on('room_created', (room: RoomItem) => {
rooms.value.unshift(room)
}),
// 房间状态更新 → 局部替换
sseBus.on('room_updated', (room: RoomItem) => {
const idx = rooms.value.findIndex((r) => r.id === room.id)
if (idx >= 0) {
rooms.value[idx] = room
}
}),
// 房间移除 → 从列表中删除
sseBus.on('room_removed', ({ roomId }: { roomId: string }) => {
rooms.value = rooms.value.filter((r) => r.id !== roomId)
})
]
onUnmounted(() => offs.forEach((fn) => fn()))
})
/** 筛选后的房间列表 */
const filteredRooms = computed(() => {
const list = rooms.value