You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
13 KiB
13 KiB
06-AI对话页面
目标
实现 AI 健康问诊对话功能,支持多轮对话和对话历史管理。
UI 设计参考
参考设计稿:
files/ui/问答页.png、files/ui/问答对话.png
对话首页布局
| 区域 | 设计要点 |
|---|---|
| 导航栏 | "AI健康助手" + 绿色 "在线" 状态 + 更多菜单 |
| AI 欢迎语 | 机器人图标(蓝色背景 #3B82F6)+ 灰色气泡 |
| 常见问题 | "常见问题" 标签(灰色)+ 快捷问题按钮(白色圆角) |
| 输入区 | 麦克风图标 + 输入框(灰色背景)+ 绿色发送按钮 |
消息气泡样式
| 类型 | 样式 |
|---|---|
| AI 消息 | 左对齐,机器人图标(蓝色 #3B82F6),灰色气泡 #F3F4F6 |
| 用户消息 | 右对齐,用户图标(绿色 #10B981),绿色气泡 #10B981,白色文字 |
| 时间显示 | 灰色小字 #9CA3AF,位于消息下方 |
输入区样式
| 元素 | 样式 |
|---|---|
| 麦克风 | 灰色图标 #9CA3AF |
| 输入框 | 灰色背景 #F3F4F6,圆角 24px,占位符 "请输入您的健康问题..." |
| 发送按钮 | 绿色圆形按钮 #10B981,飞机图标 |
快捷问题示例
- 我最近总是感觉疲劳怎么办?
- 如何改善睡眠质量?
- 有什么养生建议吗?
- 感冒了应该注意什么?
前置要求
- 体质测评页面完成
- 后端对话接口可用
实施步骤
步骤 1:创建对话 API
创建 src/api/conversation.ts:
import request from './request'
import type { Conversation, Message } from '@/types'
export const getConversations = (): Promise<Conversation[]> => {
return request.get('/conversations')
}
export const createConversation = (title?: string): Promise<Conversation> => {
return request.post('/conversations', { title })
}
export const getConversation = (id: number): Promise<Conversation & { messages: Message[] }> => {
return request.get(`/conversations/${id}`)
}
export const deleteConversation = (id: number) => {
return request.delete(`/conversations/${id}`)
}
export const sendMessage = (id: number, content: string): Promise<{ reply: string }> => {
return request.post(`/conversations/${id}/messages`, { content })
}
步骤 2:创建对话列表页面
创建 src/views/chat/Index.vue:
<template>
<div class="chat-index">
<div class="chat-header">
<h2>AI 健康问诊</h2>
<el-button type="primary" @click="createNewChat">
<el-icon><Plus /></el-icon>
新建对话
</el-button>
</div>
<div v-if="loading" class="loading">
<el-skeleton :rows="5" animated />
</div>
<div v-else-if="conversations.length === 0" class="empty-state">
<el-empty description="暂无对话记录">
<el-button type="primary" @click="createNewChat">开始第一次对话</el-button>
</el-empty>
</div>
<div v-else class="conversation-list">
<div
v-for="conv in conversations"
:key="conv.id"
class="conversation-item"
@click="openChat(conv.id)"
>
<div class="conv-icon">
<el-icon><ChatDotRound /></el-icon>
</div>
<div class="conv-content">
<div class="conv-title">{{ conv.title }}</div>
<div class="conv-time">{{ formatTime(conv.updated_at) }}</div>
</div>
<div class="conv-actions">
<el-button
type="danger"
text
size="small"
@click.stop="deleteChat(conv.id)"
>
<el-icon><Delete /></el-icon>
</el-button>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, ChatDotRound, Delete } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import type { Conversation } from '@/types'
import { getConversations, createConversation, deleteConversation } from '@/api/conversation'
const router = useRouter()
const loading = ref(true)
const conversations = ref<Conversation[]>([])
onMounted(async () => {
await loadConversations()
})
const loadConversations = async () => {
loading.value = true
try {
conversations.value = await getConversations()
} catch (error) {
// 错误已处理
} finally {
loading.value = false
}
}
const createNewChat = async () => {
try {
const conv = await createConversation()
router.push(`/chat/${conv.id}`)
} catch (error) {
// 错误已处理
}
}
const openChat = (id: number) => {
router.push(`/chat/${id}`)
}
const deleteChat = async (id: number) => {
try {
await ElMessageBox.confirm('确定要删除这个对话吗?', '提示', {
type: 'warning',
})
await deleteConversation(id)
ElMessage.success('删除成功')
conversations.value = conversations.value.filter((c) => c.id !== id)
} catch (error) {
// 取消或错误
}
}
const formatTime = (time: string) => {
return dayjs(time).format('MM-DD HH:mm')
}
</script>
<style scoped>
.chat-index {
max-width: 800px;
margin: 0 auto;
}
.chat-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 24px;
}
.loading {
background: #fff;
padding: 20px;
border-radius: 8px;
}
.empty-state {
background: #fff;
padding: 60px 20px;
border-radius: 8px;
text-align: center;
}
.conversation-list {
background: #fff;
border-radius: 8px;
overflow: hidden;
}
.conversation-item {
display: flex;
align-items: center;
padding: 16px 20px;
border-bottom: 1px solid #eee;
cursor: pointer;
transition: background 0.2s;
}
.conversation-item:hover {
background: #f9f9f9;
}
.conversation-item:last-child {
border-bottom: none;
}
.conv-icon {
width: 40px;
height: 40px;
background: #ecf5ff;
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
margin-right: 16px;
}
.conv-icon .el-icon {
font-size: 20px;
color: #409eff;
}
.conv-content {
flex: 1;
}
.conv-title {
font-size: 15px;
color: #333;
margin-bottom: 4px;
}
.conv-time {
font-size: 12px;
color: #999;
}
.conv-actions {
opacity: 0;
transition: opacity 0.2s;
}
.conversation-item:hover .conv-actions {
opacity: 1;
}
</style>
步骤 3:创建对话详情页面
创建 src/views/chat/Detail.vue:
<template>
<div class="chat-detail">
<!-- 消息列表 -->
<div ref="messagesRef" class="messages-container">
<div v-if="loading" class="loading">
<el-skeleton :rows="5" animated />
</div>
<template v-else>
<div
v-for="msg in messages"
:key="msg.id"
:class="['message-item', msg.role]"
>
<div class="avatar">
<el-avatar v-if="msg.role === 'user'" :size="36">
{{ userStore.userInfo?.nickname?.charAt(0) || 'U' }}
</el-avatar>
<el-avatar v-else :size="36" style="background: #409eff">
AI
</el-avatar>
</div>
<div class="message-content">
<div class="message-bubble" v-html="formatMessage(msg.content)"></div>
<div class="message-time">{{ formatTime(msg.created_at) }}</div>
</div>
</div>
<div v-if="sending" class="message-item assistant">
<div class="avatar">
<el-avatar :size="36" style="background: #409eff">AI</el-avatar>
</div>
<div class="message-content">
<div class="message-bubble typing">
<span></span><span></span><span></span>
</div>
</div>
</div>
</template>
</div>
<!-- 输入区域 -->
<div class="input-container">
<el-input
v-model="inputText"
type="textarea"
:rows="2"
placeholder="请描述您的健康问题..."
:disabled="sending"
@keydown.enter.exact.prevent="sendMessage"
/>
<el-button
type="primary"
:loading="sending"
:disabled="!inputText.trim()"
@click="sendMessage"
>
发送
</el-button>
</div>
<!-- 免责声明 -->
<div class="disclaimer">
<el-icon><Warning /></el-icon>
AI 建议仅供参考,不构成医疗诊断。如有不适,请及时就医。
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Warning } from '@element-plus/icons-vue'
import { marked } from 'marked'
import dayjs from 'dayjs'
import { useUserStore } from '@/stores/user'
import type { Message } from '@/types'
import { getConversation, sendMessage as sendMessageApi } from '@/api/conversation'
const route = useRoute()
const userStore = useUserStore()
const loading = ref(true)
const sending = ref(false)
const messages = ref<Message[]>([])
const inputText = ref('')
const messagesRef = ref<HTMLElement>()
const conversationId = parseInt(route.params.id as string)
onMounted(async () => {
await loadMessages()
})
const loadMessages = async () => {
loading.value = true
try {
const data = await getConversation(conversationId)
messages.value = data.messages || []
await nextTick()
scrollToBottom()
} catch (error) {
ElMessage.error('加载对话失败')
} finally {
loading.value = false
}
}
const sendMessage = async () => {
const content = inputText.value.trim()
if (!content || sending.value) return
// 添加用户消息
const userMessage: Message = {
id: Date.now(),
role: 'user',
content,
created_at: new Date().toISOString(),
}
messages.value.push(userMessage)
inputText.value = ''
await nextTick()
scrollToBottom()
// 发送请求
sending.value = true
try {
const res = await sendMessageApi(conversationId, content)
// 添加 AI 回复
const assistantMessage: Message = {
id: Date.now() + 1,
role: 'assistant',
content: res.reply,
created_at: new Date().toISOString(),
}
messages.value.push(assistantMessage)
await nextTick()
scrollToBottom()
} catch (error) {
// 移除用户消息
messages.value.pop()
inputText.value = content
} finally {
sending.value = false
}
}
const scrollToBottom = () => {
if (messagesRef.value) {
messagesRef.value.scrollTop = messagesRef.value.scrollHeight
}
}
const formatMessage = (content: string) => {
return marked.parse(content)
}
const formatTime = (time: string) => {
return dayjs(time).format('HH:mm')
}
</script>
<style scoped>
.chat-detail {
display: flex;
flex-direction: column;
height: calc(100vh - 140px);
max-width: 800px;
margin: 0 auto;
background: #fff;
border-radius: 8px;
overflow: hidden;
}
.messages-container {
flex: 1;
overflow-y: auto;
padding: 20px;
}
.loading {
padding: 20px;
}
.message-item {
display: flex;
margin-bottom: 20px;
}
.message-item.user {
flex-direction: row-reverse;
}
.avatar {
flex-shrink: 0;
}
.message-content {
max-width: 70%;
margin: 0 12px;
}
.message-bubble {
padding: 12px 16px;
border-radius: 12px;
line-height: 1.6;
}
.user .message-bubble {
background: #409eff;
color: #fff;
border-top-right-radius: 4px;
}
.assistant .message-bubble {
background: #f4f4f5;
color: #333;
border-top-left-radius: 4px;
}
.message-time {
font-size: 11px;
color: #999;
margin-top: 4px;
}
.user .message-time {
text-align: right;
}
/* 打字动画 */
.typing {
display: flex;
gap: 4px;
padding: 16px 20px;
}
.typing span {
width: 8px;
height: 8px;
background: #999;
border-radius: 50%;
animation: typing 1s infinite;
}
.typing span:nth-child(2) {
animation-delay: 0.2s;
}
.typing span:nth-child(3) {
animation-delay: 0.4s;
}
@keyframes typing {
0%, 100% { opacity: 0.3; }
50% { opacity: 1; }
}
.input-container {
display: flex;
gap: 12px;
padding: 16px 20px;
border-top: 1px solid #eee;
}
.input-container .el-textarea {
flex: 1;
}
.disclaimer {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
padding: 12px;
background: #fef0f0;
color: #f56c6c;
font-size: 12px;
}
</style>
步骤 4:安装 marked 库
npm install marked
npm install @types/marked -D
需要创建的文件清单
| 文件路径 | 说明 |
|---|---|
src/api/conversation.ts |
对话 API |
src/views/chat/Index.vue |
对话列表页 |
src/views/chat/Detail.vue |
对话详情页 |
验收标准
- 对话列表正确显示
- 新建对话功能正常
- 消息发送和接收正常
- AI 回复正确渲染 Markdown
- 打字动画效果正常
- 免责声明显示
预计耗时
35-40 分钟
下一步
完成后进入 03-Web前端开发/07-个人中心页面.md