kongdeqiang
2026-10-12 97ddb98e522b2a15026e174be14a721219db4623
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<template>
  <div class="chat-page">
    <Sidebar
      v-show="sidebarVisible"
      ref="sidebarRef"
      @select="handleSelectChat"
      @created="handleCreated"
      @deleted="handleDeleted"
      @open-files="handleOpenFiles"
      @open-admin-knowledge="handleOpenAdminKnowledge"
    />
    <ChatView :chat-id="chatId" ref="chatViewRef" @toggle-sidebar="sidebarVisible = !sidebarVisible" />
  </div>
</template>
 
<script setup>
import { onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import Sidebar from '@/components/Sidebar.vue'
import ChatView from '@/components/ChatView.vue'
import { useAuthStore } from '@/stores/authStore'
import { useChatStore } from '@/stores/chatStore'
 
const route = useRoute()
const router = useRouter()
const message = useMessage()
const auth = useAuthStore()
const chatStore = useChatStore()
 
const sidebarRef = ref(null)
const chatViewRef = ref(null)
const sidebarVisible = ref(true)
 
// 会话 id 来自路由参数,字符串需转成数字
const chatId = ref(route.params.chatId ? Number(route.params.chatId) : null)
 
onMounted(async () => {
  // 刷新页面后校验 token 是否仍然有效(失效会由拦截器登出)
  await auth.fetchMe()
  await sidebarRef.value?.refresh()
 
  // 没有指定会话时,自动选中最近的一个,避免用户看到空白页
  if (!chatId.value && chatStore.chats.length > 0) {
    router.replace(`/c/${chatStore.chats[0].id}`)
  }
})
 
// 路由与会话状态双向同步
watch(
  () => route.params.chatId,
  (value) => {
    const next = value ? Number(value) : null
    if (next !== chatId.value) {
      chatId.value = next
    }
  }
)
 
function handleSelectChat(id) {
  if (id === chatId.value) return
  router.push(`/c/${id}`)
}
 
function handleCreated(id) {
  router.push(`/c/${id}`)
}
 
function handleDeleted(id) {
  // 删掉的正好是当前会话,或者用户登出:回到空白页
  if (id === null || id === chatId.value) {
    router.push('/c')
  }
}
 
function handleOpenFiles() {
  router.push('/files')
}
 
function handleOpenAdminKnowledge() {
  router.push('/admin/knowledge')
}
 
// 兜底:路由指向不存在的会话时提示并清理
watch(chatId, async (id) => {
  if (!id) return
 
  const inMain = chatStore.chats.some((chat) => chat.id === id)
  // 归档的会话不在主列表里,但仍然是有效会话 ——
  // 只看主列表会把「打开一个归档对话」误判成「对话已被删除」
  const inArchive = chatStore.archivedChats.some((chat) => chat.id === id)
 
  // 归档列表还没加载完时不做判定:宁可晚一点提示,也不要误报
  if (inMain || inArchive || !chatStore.archiveLoaded || chatStore.chats.length === 0) {
    return
  }
 
  message.warning('该对话不存在或已被删除')
  router.replace('/c')
})
</script>
 
<style scoped>
.chat-page {
  display: flex;
  height: 100vh;
  overflow: hidden;
}
</style>