Vue 3.5 + Vite 7 Web AI Chat System: A Practical Guide
This article explains how to build a web-based AI chat application with Vue 3.5 and Vite 7, covering the technology stack, layered architecture, SSE streaming output, reasoning mode, Markdown and rich-text rendering, theme switching, and engineering considerations. It provides a practical reference for implementing core chat features and organizing a maintainable frontend project.
1. Project Background and Technology Selection
The growing availability of large model APIs has made web-based AI chat systems a popular frontend practice area. Compared with using a general-purpose chat product directly, a self-built system offers customizable interaction patterns, private deployment options, and the ability to extend plugin capabilities for specific business scenarios.
The core technology stack in this solution is as follows:
- Build tool: Use the latest major version of a next-generation build tool (v7.x), taking advantage of native ESM and on-demand compilation. Cold start and hot update performance are significantly better than traditional bundling approaches.
- View framework: Use Vue 3.5. Its reactivity system has been optimized over multiple iterations, and the Composition API helps organize complex state logic such as conversation flows and session management more clearly.
- Routing and state management: The routing layer handles switching between multi-session pages. Pinia manages global data such as session lists, message records, and user preferences. A persistence plugin writes conversation history to local storage so context is not lost after a page refresh.
- UI component library: Use a mature desktop UI component library for dialogs, drawers, forms, and other basic interactions to reduce custom development effort.
- Large model integration: Connect to mainstream large model services through an OpenAI-compatible chat API, including standard chat mode and deep reasoning mode.
2. Core Architecture Design
2.1 Layered Structure
It is recommended to divide the project into four layers:
- Access layer: Encapsulates large model requests and uniformly handles authentication, timeouts, retries, and streaming parsing.
- Session layer: Maintains the multi-session list, message pagination, and context truncation strategies.
- Rendering layer: Handles Markdown parsing, code highlighting, formula rendering, and diagram rendering.
- Interaction layer: Contains UI logic such as theme switching, the input area, message bubbles, and scroll following.
2.2 Directory Organization
src/├── api/ # Large model API wrappers├── store/ # Session and settings state├── components/ # Message bubbles, input box, sidebar├── composables/ # useChat, useStream, useTheme├── styles/ # Dark/light theme variables└── views/ # Main conversation page
3. Streaming Output Implementation
Streaming output is central to the chat experience. Mainstream large model APIs commonly return incremental content in SSE (Server-Sent Events) format, and the frontend needs to parse and append it segment by segment.
Key implementation points:
async function sendStream(messages, onDelta) {const res = await fetch('/v1/chat/completions', {method: 'POST',headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },body: JSON.stringify({ model, messages, stream: true })})const reader = res.body.getReader()const decoder = new TextDecoder()let buffer = ''while (true) {const { done, value } = await reader.read()if (done) breakbuffer += decoder.decode(value, { stream: true })// Split event frames by \n\n according to the SSE protocolconst frames = buffer.split('\n\n')buffer = frames.pop()for (const frame of frames) {const data = frame.replace(/^data: /, '')if (data === '[DONE]') returnconst json = JSON.parse(data)const delta = json.choices?.[0]?.delta?.contentif (delta) onDelta(delta)}}}
Practical considerations:
- Abort control: Use
AbortControllerto let users stop generation manually and avoid unnecessary waiting. - Render throttling: High-frequency deltas can trigger re-renders and cause jank. Combine increments within each 50–100 ms before updating the view.
- Scroll following: Automatically scroll to the bottom only when the user has not scrolled up manually, so reading is not interrupted.
4. Deep Reasoning Mode
Reasoning models output reasoning content before the final answer. The frontend needs to distinguish between two types of incremental fields: reasoning content is displayed in a collapsible panel, while the final answer is rendered normally. In practice, the message object can be extended with a reasoning field. When reasoning fragments arrive, write them to that field; when answer fragments arrive, write them to content. The rendering layer uses a collapsible component to present the reasoning process and can show a “thinking” animation. This design can significantly improve user trust in the AI reasoning process.
5. Rich-Text Rendering Capabilities
Conversation content often includes code, formulas, and diagrams, requiring a complete Markdown rendering pipeline:
- Markdown parsing: Configure HTML escaping with a general-purpose parser to prevent XSS injection.
- Code highlighting and copying: Apply a highlighting library to code blocks and attach a copy button to the top-right corner, with feedback after a successful copy.
- Mathematical formulas: Integrate the KaTeX plugin to support both inline
$...$and block$$...$$syntax. - Diagram rendering: Detect Mermaid code blocks and initialize diagrams asynchronously after rendering. If initialization fails, fall back to displaying the source code.
6. Theme and Engineering Details
Define design tokens with CSS variables. Toggle the data-theme attribute on the root node to achieve smooth transitions between dark and light themes. Code highlighting themes also need to switch accordingly. Additional recommendations:
- Do not place API keys in plaintext in the frontend; forward requests through a backend gateway proxy.
- Pay attention to capacity control when persisting conversation history.
- Apply context trimming to long conversations to control token costs.
7. Conclusion
This solution covers the main technical aspects of building a web-based AI chat system: streaming output ensures a responsive experience, deep reasoning improves transparency, rich-text rendering enhances professionalism, and the theme system refines the details. Based on this skeleton, developers can further extend capabilities such as web search, tool calling, and multi-model switching, gradually evolving the system into an intelligent chat product for real business scenarios.
