Vue 3 重构 Dify 聊天前端:项目搭建与基础架构
介绍使用 Vue 3 和 TypeScript 从零构建类似 Dify 的 AI 聊天前端项目。内容涵盖项目初始化、Vite 配置、TypeScript 类型体系设计(消息、文件、Agent 思考过程、工作流追踪)、路由与 SSO 认证流程、Axios HTTP 客户端封装以及 Pinia 状态管理(用户与会话)。重点解决了 SSE 流式输出、Markdown 渲染及移动端适配的基础架构问题,为后续实现核心聊天功能奠定基础。

介绍使用 Vue 3 和 TypeScript 从零构建类似 Dify 的 AI 聊天前端项目。内容涵盖项目初始化、Vite 配置、TypeScript 类型体系设计(消息、文件、Agent 思考过程、工作流追踪)、路由与 SSO 认证流程、Axios HTTP 客户端封装以及 Pinia 状态管理(用户与会话)。重点解决了 SSE 流式输出、Markdown 渲染及移动端适配的基础架构问题,为后续实现核心聊天功能奠定基础。

本系列教程将带你从零开始,用 Vue 3 + TypeScript 复刻一个类似 Dify 的 AI 聊天前端。上篇聚焦项目搭建、类型设计、路由认证、HTTP 封装和状态管理。


Dify 是一个开源的 LLM 应用开发平台,提供了对话式 AI 的后端服务。在实际项目中,我们往往需要自建前端来对接 Dify 后端 API 或 LLM 后端服务,实现定制化的聊天界面。
本项目的目标:用 Vue 3 构建一个生产级的 AI 聊天前端,具备以下能力:
| 类别 | 技术选型 | 说明 |
|---|---|---|
| 框架 | Vue 3.4 + Composition API | 使用 |
| 语言 | TypeScript 5.3 | 全量类型覆盖 |
| 构建 | Vite 5.1 | 极速 HMR |
| 状态管理 | Pinia 2.1 | Composition API 风格 |
| UI 库 | Element Plus 2.5 | 成熟的 Vue 3 组件库 |
| HTTP | Axios 1.6 | 请求拦截 + 统一错误处理 |
| Markdown | marked 12 + highlight.js 11 | GFM 渲染 + 代码高亮 |
| 安全 | DOMPurify 3.0 | XSS 防护 |
| 样式 | SCSS | CSS 变量 + 响应式 |
src/
├── api/ # API 层
│ ├── app.ts # 应用信息接口
│ ├── chat.ts # 聊天 API + SSE 流式
│ └── user.ts # 用户认证接口
├── assets/ # 静态资源
├── components/ # 可复用组件(9 个)
│ ├── AgentThought.vue # Agent 思考过程
│ ├── ChatSidebar.vue # 侧边栏
│ ├── ConversationItem.vue # 会话条目
│ ├── FeedbackButtons.vue # 反馈按钮
│ ├── FileUpload.vue # 文件上传
│ ├── MarkdownRenderer.vue # Markdown 渲染
│ ├── MessageActions.vue # 消息操作
│ ├── SuggestedQuestions.vue # 建议问题
│ └── WorkflowTracing.vue # 工作流可视化
├── router/ # 路由配置
│ └── index.ts
├── stores/ # Pinia 状态管理
│ ├── conversation.ts # 会话状态
│ └── user.ts # 用户状态
├── styles/ # 全局样式
├── utils/ # 工具函数
│ └── request.ts # Axios 封装
├── views/ # 页面组件
│ ├── ChatView.vue # 主聊天页面
│ └── ErrorView.vue # 错误页面
├── main.ts # 入口文件
└── App.vue # 根组件
用户输入 → ChatView → sendChatMessageSSE() → Dify API
↑ ↓
messages 数组 ← SSE 事件流(message/agent_thought/workflow)
↓
MarkdownRenderer → 实时渲染 AI 回复
npm create vite@latest dify-chat -- --template vue-ts
cd dify-chat
npm install
# 核心依赖
npm install vue-router pinia axios element-plus @element-plus/icons-vue
# Markdown 与代码高亮
npm install marked highlight.js dompurify
# 开发依赖
npm install -D sass @types/dompurify
vite.config.ts 是整个项目的构建核心:
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd())
return {
// 支持子路径部署(如 /chat-app/)
base: env.VITE_APP_NGINX_SUB_PATH || '/',
plugins: [vue()],
css: {
preprocessorOptions: {
scss: {
api: 'modern-compiler' // 使用现代 SCSS 编译器
}
}
},
resolve: {
alias: {
'@': '/src' // 路径别名,import xx from '@/utils/xx'
}
},
server: {
port: 3001,
proxy: {
// 开发环境将 /api 请求代理到后端
'/api': {
target: 'http://localhost:9000',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
}
}
})
关键设计决策:
/api/* 请求自动转发到后端,避免跨域问题。@/ 映射到 src/,让导入路径更清晰。VITE_APP_NGINX_SUB_PATH 控制 base path,适配不同部署环境。创建 .env 文件:
VITE_APP_TITLE=AI 智能助手
VITE_API_BASE_URL=/api
VITE_APP_NGINX_SUB_PATH=/
TypeScript 类型声明 src/env.d.ts:
interface ImportMetaEnv {
readonly VITE_APP_TITLE: string
readonly VITE_API_BASE_URL: string
readonly VITE_APP_NGINX_SUB_PATH: string
}
类型设计是整个项目的基础。我们把所有聊天相关的类型集中在 src/api/chat.ts 中定义。
// 前端使用的消息结构
export interface Message {
id: string
role: 'user' | 'assistant'
content: string
createAt?: number
parentMessageId?: string
messageFiles?: MessageFile[]
agentThoughts?: AgentThought[]
workflow_process?: WorkflowProcess
feedback?: Feedback
citation?: Citation[]
}
// 后端返回的消息结构(需要转换)
export interface BackendMessage {
id: string
conversationId: string
parentMessageId: string
inputs: Record<string, any>
query: string // 用户问题
answer: string // AI 回答
messageFiles: MessageFile[]
feedback: Feedback | null
retrieverResources: any[]
agentThoughts: AgentThought[]
createdAt:
:
: |
}
为什么要区分 Message 和 BackendMessage?
后端返回的是'一轮对话'的结构(包含 query + answer),而前端渲染需要拆分为 user 和 assistant 两条独立消息。这个转换在 getMessages 函数中完成。
export interface MessageFile {
id: string
type: string // 'image' | 'document' 等
url: string
filename?: string
size?: number
}
export interface AgentThought {
id: string
thought: string // 思考内容
tool?: string // 调用的工具名称
tool_input?: string // 工具输入参数
observation?: string // 工具执行结果
message_files?: MessageFile[]
created_at?: number
}
export interface WorkflowProcess {
status: string // 'running' | 'succeeded' | 'failed'
tracing: WorkflowNode[]
}
export interface WorkflowNode {
id: string
node_id: string
title: string // 节点名称,如'大模型'、'知识检索'
status: string // 'running' | 'succeeded' | 'failed'
inputs?: any
outputs?: any
elapsed_time?: number // 执行耗时(秒)
}
export interface Feedback {
rating: 'like' | 'dislike' | null
content?: string // 详细反馈内容
}
export interface Citation {
position: number
document_id: string
document_name: string
data_source_type: string
source_url?: string
}
export interface ChatRequest {
appId: string
query: string
conversationId?: string // 有值表示继续已有会话
inputs?: Record<string, any>
files?: string[] // 已上传文件的 URL 列表
}
这是整个流式聊天的核心类型定义——通过回调函数把不同类型的 SSE 事件分发到对应的处理逻辑:
export interface SSECallbacks {
onMessage: (content: string, taskId?: string, messageId?: string) => void
onThought: (thought: AgentThought) => void
onFile: (file: MessageFile) => void
onMessageEnd: (data: { messageId: string; conversationId: string; citation?: Citation[]; feedback?: Feedback }) => void
onWorkflowStarted: (data: { workflowRunId: string; taskId: string; conversationId: string }) => void
onNodeStarted: (node: WorkflowNode) => void
onNodeFinished: (node: WorkflowNode) => void
onWorkflowFinished: (data: { status: string; conversationId: }) =>
:
:
:
:
}
这种设计的好处:SSE 解析逻辑与 UI 更新逻辑完全解耦。sendChatMessageSSE 函数只负责解析 SSE 流并触发回调,而 ChatView 组件通过回调函数决定如何更新 UI。
src/router/index.ts:
import { createRouter, createWebHistory } from 'vue-router'
import { getInfo, ssoLogin } from '@/api/user'
import { useUserStore } from '@/stores/user'
const router = createRouter({
history: createWebHistory(import.meta.env.VITE_APP_NGINX_SUB_PATH),
routes: [
{
path: '/',
redirect: '/error?message=请从安溪专区访问'
},
{
path: '/chat/:appId', // 动态路由,支持多应用
name: 'Chat',
component: () => import('@/views/ChatView.vue') // 懒加载
},
{
path: '/error',
name: 'Error',
component: () => import('@/views/ErrorView.vue')
}
]
})
设计要点:
/chat/:appId 使用动态路由,同一个前端可以对接不同的 AI 应用(每个应用有不同的 prompt、模型配置等)。() => import()),首屏不会加载所有页面代码。通过路由守卫 beforeEach 实现 SSO 认证流程:
router.beforeEach(async (to, from, next) => {
const userStore = useUserStore()
const ssoApp = to.query.appid as string
const ssoCode = to.query.code as string
let token = userStore.token // 开发环境自动 mock
if (import.meta.env.DEV) {
const devToken = 'eyJhbGciOiJIUzI1NiJ9...'
userStore.setToken(devToken)
userStore.setUserInfo({ ssoUserName: 'dev_user', nickName: '开发测试用户' })
token = devToken
}
if (ssoApp && ssoCode && !token) {
try {
// 1. 用 SSO code 换取 token
const newToken = await ssoLogin(ssoApp, ssoCode)
userStore.setToken(newToken)
// 2. 获取用户信息
const userInfo = await getInfo()
userStore.setUserInfo(userInfo)
// 3. 去掉 URL 中的 code 参数,刷新路由
const query = { ...to.query }
delete query.code
next({ ...to, query, replace: })
} (error) {
({ : , : { : } })
}
} (!token && to. !== ) {
({ : , : { : } })
} {
()
}
})
SSO 认证流程图:
门户入口 → 带 appid + code 参数访问 /chat/xxx
↓
beforeEach 拦截 → 检测到 code
↓
ssoLogin(appid, code) → 获取 token
↓
getInfo() → 获取用户信息
↓
存储 token + userInfo → 重定向(去掉 code 参数)
↓
进入 ChatView 正常聊天
src/utils/request.ts:
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { TOKEN_KEY, useUserStore } from '@/stores/user'
const request = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL, // '/api'
timeout: 120000 // 2 分钟超时,AI 响应可能较慢
})
核心功能:自动注入 Bearer Token。
request.interceptors.request.use((config) => {
const token = localStorage.getItem(TOKEN_KEY)
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
}, (error) => Promise.reject(error))
这里直接从 localStorage 读取 token,而不是从 Pinia store 读取,是为了避免循环依赖问题(store 还未初始化时就需要发请求)。
统一处理后端返回的业务错误码:
request.interceptors.response.use(
(res) => {
const code = res.data.code || 200
const msg = errorCode[code] || res.data.msg || errorCode['default']
// 二进制数据直接返回
if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
return res.data
}
const userStore = useUserStore()
if (code === 401) {
// 认证过期 → 清除登录状态 + 弹窗提示
userStore.logout()
return ElMessageBox.alert('登录状态已过期,请重新从门户点击访问!', '认证失败').then(() => Promise.reject('无效的会话'))
} else if (code === 500) {
ElMessage.error(msg)
return Promise.reject(new Error(msg))
} else if (code === 601) {
ElMessage.(msg)
.()
} (code !== ) {
.(msg)
.()
} {
res..
}
},
{
.(error)
.(error)
}
)
关键设计:
data 字段的值。有了封装好的 request,API 函数写起来非常简洁:
// src/api/app.ts
export const getAppById = async (id: string): Promise<AppInfo> => {
return await request.get(`/app/${id}`)
}
// src/api/user.ts
export const ssoLogin = async (ssoApp: string, ssoCode: string): Promise<string> => {
return await request.get('/public/login/ssoLogin', {
params: { ssoApp, ssoCode }
})
}
export const getInfo = async (): Promise<UserInfo> => {
return await request.get('/user/getInfo')
}
src/stores/user.ts — 使用 Composition API 风格(defineStore + setup 函数):
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const TOKEN_KEY = 'ai-token'
export const USER_INFO_KEY = 'ai-userInfo'
export const useUserStore = defineStore('user', () => {
const userInfo = ref<UserInfo | null>(null)
const token = ref<string>('')
// 设置 Token → 同时持久化到 localStorage
const setToken = (value: string) => {
token.value = value
localStorage.setItem(TOKEN_KEY, value)
}
// 设置用户信息 → 同步持久化
const setUserInfo = (info: UserInfo) => {
userInfo.value = info
localStorage.setItem(USER_INFO_KEY, JSON.stringify(info))
}
// 从 localStorage 恢复(页面刷新后)
const initFromStorage = () => {
const storedToken = .()
storedUserInfo = .()
(storedToken) token. = storedToken
(storedUserInfo) {
{
userInfo. = .(storedUserInfo)
} {
userInfo. =
}
}
}
= () => {
userInfo. =
token. =
.()
.()
}
{
userInfo,
token,
setToken,
setUserInfo,
initFromStorage,
logout
}
})
设计要点:
initFromStorage 在应用启动时调用(main.ts 中),确保路由守卫能拿到 token。src/stores/conversation.ts — 管理会话列表和消息:
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import {
getConversations,
getMessages,
deleteConversation as deleteConversationApi,
pinConversation as pinConversationApi,
unpinConversation as unpinConversationApi,
updateConversationName
} from '@/api/chat'
export const useConversationStore = defineStore('conversation', () => {
// === 状态 ===
const appId = ref<string>('')
const conversations = ref<ConversationItem[]>([])
const pinnedConversations = ref<ConversationItem[]>([])
const currentConversationId = ref<string>('')
const currentMessages = ref<any[]>([])
const isLoading = ref(false)
const isLoadingMessages = ref(false)
// === 计算属性 ===
// 置顶 + 普通合并后的完整列表
const allConversations = computed(() => [...pinnedConversations.value, ...conversations.value])
// 当前选中的会话对象
const currentConversation = computed(() => allConversations.value.( c. === currentConversationId.))
= () => {
(!appId.)
isLoading. =
{
conversations. = (appId., )
} {
isLoading. =
}
}
= () => {
(conversationId === currentConversationId.)
currentConversationId. = conversationId
currentMessages. = []
(conversationId) (conversationId)
}
= () => {
(!appId.)
isLoadingMessages. =
{
currentMessages. = (appId., conversationId)
} {
isLoadingMessages. =
}
}
= () => {
currentConversationId. =
currentMessages. = []
}
= () => {
(conversationId)
conversations. = conversations..( c. !== conversationId)
pinnedConversations. = pinnedConversations..( c. !== conversationId)
(currentConversationId. === conversationId) {
()
}
}
= () => {
currentConversationId. = conversationId
}
= () => {
currentMessages..(message)
}
= () => {
lastMsg = currentMessages.[currentMessages.. - ]
(lastMsg) {
lastMsg. = content
.(lastMsg, extras)
}
}
{
appId,
conversations,
pinnedConversations,
currentConversationId,
currentMessages,
isLoading,
isLoadingMessages,
currentConversation,
allConversations,
setAppId,
loadConversations,
switchConversation,
createNewConversation,
deleteConversation,
updateCurrentConversationId,
addMessage,
updateLastMessage,
renameConversation,
pinConversation,
unpinConversation
}
})
架构决策:
updateLastMessage,这是 SSE 流式更新的关键。每个 message 事件到达时,只需更新最后一条消息的 content。addMessage + updateLastMessage 组合使用:发送消息时先 addMessage 一个空的 assistant 消息占位,然后 SSE 回调不断 updateLastMessage 追加内容。这个转换发生在 src/api/chat.ts 的 getMessages 函数中:
export const getMessages = async (appId: string, conversationId: string): Promise<Message[]> => {
const backendMessages: BackendMessage[] = await request.post('/chat/message/messages', {
appId,
conversationId,
limit: 50
})
const messages: Message[] = []
backendMessages.forEach(m => {
// 后端一轮对话 = 一条 BackendMessage
// 前端需要拆成 user + assistant 两条 Message
messages.push({
id: `${m.id}-user`,
role: 'user',
content: m.query, // 用户问题
createAt: m.createdAt,
messageFiles: m.messageFiles
})
messages.push({
id: `${m.id}-assistant`,
role: 'assistant',
content: m.answer, // AI 回答
createAt: m.createdAt,
agentThoughts: m.agentThoughts,
feedback: m. || ,
: m.
})
})
messages
}
上篇我们完成了:
下一篇预告:中篇将深入核心功能——SSE 流式聊天的完整实现、ChatView 组件的核心逻辑、Markdown 渲染、文件上传和会话管理。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML 转 Markdown 互为补充。 在线工具,Markdown 转 HTML在线工具,online
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML 转 Markdown在线工具,online