refactor(views): 重构多个视图组件代码结构,优化类型定义和逻辑组织

feat(services): 新增文章分页查询方法,支持按状态筛选文章

style(styles): 调整主布局样式,优化分页组件显示效果

docs(README): 更新API文档,完善服务模块说明和类型定义

fix(components): 修复左侧模块点击属性时使用错误字段名的问题

chore(package): 移除未使用的依赖项,清理项目依赖

perf(layouts): 优化主布局组件性能,拆分功能模块,减少重复计算

test(views): 为分页组件添加基础测试用例

build: 更新构建配置,优化生产环境打包

ci: 调整CI配置,添加类型检查步骤
This commit is contained in:
qingfeng1121
2025-11-14 15:30:29 +08:00
parent 4ae0ff7c2a
commit 1dc5bdd93f
16 changed files with 1883 additions and 2456 deletions

View File

@@ -1,335 +1,440 @@
# 前端调用文档
# 前端API调用文档
## 项目概述
这是一个基于Vue 3的博客前端项目提供文章展示、分类浏览、留言板等功能。项目使用Vue 3 Composition API进行开发集成了Vue Router进行路由管理并使用Element Plus等UI库提供用户界面。
这是一个基于Vue 3的博客前端项目提供文章展示、分类管理、留言板、用户认证和疯言疯语等功能。项目使用Vue 3 Composition API进行开发集成了Vue Router进行路由管理并使用Element Plus等UI库提供用户界面。
## 技术栈
- **前端框架**: Vue 3
- **构建工具**: Vite
- **路由管理**: Vue Router 4
- **UI组件库**: Element Plus、Ant Design Vue
- **UI组件库**: Element Plus
- **HTTP客户端**: Axios
- **编程语言**: JavaScript/TypeScript
- **类型定义**: TypeScript类型接口
## 项目结构
```
src/
├── App.vue # 应用根组件
├── assets/ # 静态资源
│ └── index.css # 全局样式
├── img/ # 图片资源
├── index.vue # 首页主组件
├── main.js # 应用入口文件
├── router/ # 路由配置
│ └── Router.js # 路由定义
└── views/ # 视图组件
├── aboutme.vue # 关于页面
├── aericle.vue # 文章分类目录页面
├── articlecontents.vue # 文章内容页面
├── home.vue # 首页内容组件
├── leftmodlue.vue # 左侧边栏组件
├── messageboard.vue # 留言板页面
└── nonsense.vue # 疯言疯语页面
├── services/ # API服务模块
│ ├── apiService.js # 基础API服务配置
├── articleService.js # 文章相关API
├── categoryService.js # 分类相关API
├── categoryAttributeService.js # 分类属性相关API
├── loginService.js # 用户认证相关API
├── messageService.js # 留言相关API
├── nonsenseService.js # 疯言疯语相关API
└── index.js # 服务导出文件
├── types/ # 类型定义
│ └── index.ts # 所有接口类型定义
├── views/ # 视图组件
└── components/ # 可复用组件
```
## 路由配置
## API服务模块详解
路由配置位于 `src/router/Router.js`,定义了应用的所有路由映射关系:
### 1. 基础API服务 (apiService.js)
| 路由路径 | 组件 | 功能描述 |
|---------|------|---------|
| `/` | home.vue | 默认路由,重定向到首页 |
| `/:type` | home.vue | 首页可根据type参数筛选文章 |
| `/aericle` | aericle.vue | 文章分类目录页面 |
| `/nonsense` | nonsense.vue | 疯言疯语页面 |
| `/message` | messageboard.vue | 留言板页面 |
| `/about` | aboutme.vue | 关于页面 |
| `/articlecontents/:url` | articlecontents.vue | 文章内容详情页 |
## 主要组件说明
### 1. App.vue
应用根组件,负责渲染主页面组件。
```vue
<template>
<Index/>
</template>
<script setup>
import Index from './index.vue';
</script>
```
### 2. index.vue
主页面组件包含顶部导航栏、Hero区域和内容展示区。
主要功能:
- 响应式布局,适配不同屏幕宽度
- 导航菜单切换不同页面
- 打字机效果展示欢迎语
### 3. home.vue
首页文章列表组件,用于展示文章卡片列表。
主要功能:
- 展示文章标题、作者、发布时间等信息
- 点击文章卡片跳转到文章详情页
- 支持文章筛选功能
### 4. aericle.vue
文章分类目录组件,展示文章的分类结构。
主要功能:
- 展示不同分类下的文章数量
- 点击分类项可以跳转到对应的文章列表
### 5. articlecontents.vue
文章内容详情组件,用于展示单篇文章的完整内容。
主要功能:
- 获取URL参数并展示对应文章内容
- 支持通过参数向服务器请求相关文章
### 6. messageboard.vue
留言板组件,支持用户发表评论和回复。
主要功能:
- 展示留言列表和回复
- 支持发表新留言
- 支持回复他人留言
### 7. nonsense.vue
疯言疯语组件,展示一些非正式的简短内容。
## 后端API接口
项目后端基于Spring Boot开发提供了以下主要API接口
### 文章管理API
#### 1. 获取文章列表
```
GET /api/articles
```
**功能**: 获取所有文章列表
**返回**: 包含文章列表的ResponseMessage对象
#### 2. 获取单篇文章
```
GET /api/articles/{id}
```
**功能**: 根据ID获取单篇文章详情
**参数**: id - 文章ID
**返回**: 包含文章信息的ResponseMessage对象
#### 3. 根据分类获取文章
```
GET /api/articles/category/{categoryId}
```
**功能**: 获取指定分类下的所有文章
**参数**: categoryId - 分类ID
**返回**: 包含文章列表的ResponseMessage对象
#### 4. 获取热门文章
```
GET /api/articles/popular
```
**功能**: 获取浏览量最高的文章列表
**返回**: 包含热门文章列表的ResponseMessage对象
#### 5. 创建文章 (需要认证)
```
POST /api/articles
```
**功能**: 创建新文章
**权限**: 需要AUTHOR角色
**参数**: ArticleDto对象 (JSON格式)
**返回**: 包含新创建文章信息的ResponseMessage对象
#### 6. 更新文章 (需要认证)
```
PUT /api/articles/{id}
```
**功能**: 更新现有文章
**权限**: 需要AUTHOR或ADMIN角色
**参数**:
- id - 文章ID
- ArticleDto对象 (JSON格式)
**返回**: 包含更新后文章信息的ResponseMessage对象
#### 7. 删除文章 (需要认证)
```
DELETE /api/articles/{id}
```
**功能**: 删除指定文章
**权限**: 需要AUTHOR或ADMIN角色
**参数**: id - 文章ID
**返回**: 包含被删除文章信息的ResponseMessage对象
### 留言管理API
#### 1. 获取所有留言
```
GET /api/messages
```
**功能**: 获取所有留言列表
**返回**: 包含留言列表的ResponseMessage对象
#### 2. 获取单条留言
```
GET /api/messages/{id}
```
**功能**: 根据ID获取单条留言详情
**参数**: id - 留言ID
**返回**: 包含留言信息的ResponseMessage对象
#### 3. 保存留言
```
POST /api/messages
```
**功能**: 保存新留言
**参数**: MessageDto对象 (JSON格式)
**返回**: 包含保存后留言信息的ResponseMessage对象
#### 4. 删除留言
```
DELETE /api/messages/{id}
```
**功能**: 删除指定留言
**参数**: id - 留言ID
**返回**: 包含删除结果的ResponseMessage对象
## 前端API调用说明
项目中使用Axios进行HTTP请求推荐创建统一的API服务模块来封装所有后端API调用。以下是一个示例
基础API服务配置了Axios实例设置请求拦截器和响应拦截器统一处理认证信息和错误响应。
```javascript
import axios from 'axios';
// 创建axios实例
const api = axios.create({
baseURL: 'http://localhost:8080/api', // 后端API基础URL
baseURL:'http://localhost:8080/api', // API基础URL
timeout: 10000, // 请求超时时间
headers: {
'Content-Type': 'application/json'
}
});
// 请求拦截器
api.interceptors.request.use(
config => {
// 可以在这里添加token等认证信息
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
error => {
return Promise.reject(error);
}
);
// 响应拦截器
api.interceptors.response.use(
response => {
return response.data;
},
error => {
// 统一错误处理
console.error('API请求错误:', error);
return Promise.reject(error);
}
);
// 文章相关API
export const articleAPI = {
// 获取所有文章
getAllArticles: () => api.get('/articles'),
// 获取单篇文章
getArticleById: (id) => api.get(`/articles/${id}`),
// 根据分类获取文章
getArticlesByCategory: (categoryId) => api.get(`/articles/category/${categoryId}`),
// 获取热门文章
getPopularArticles: () => api.get('/articles/popular'),
// 创建文章
createArticle: (articleData) => api.post('/articles', articleData),
// 更新文章
updateArticle: (id, articleData) => api.put(`/articles/${id}`, articleData),
// 删除文章
deleteArticle: (id) => api.delete(`/articles/${id}`)
};
// 留言相关API
export const messageAPI = {
// 获取所有留言
getAllMessages: () => api.get('/messages'),
// 获取单条留言
getMessageById: (id) => api.get(`/messages/${id}`),
// 保存留言
saveMessage: (messageData) => api.post('/messages', messageData),
// 删除留言
deleteMessage: (id) => api.delete(`/messages/${id}`)
};
// 导出默认的api对象
export default api;
withCredentials: true // 允许跨域请求携带凭证
})
```
**核心功能**
- 自动添加认证token到请求头
- 统一处理HTTP错误401、403、404、500等
- 自动显示错误提示信息
- 未授权时自动清除token并重定向到登录页
### 2. 文章服务 (articleService.js)
提供文章的CRUD操作和各种查询功能。
**主要方法**
| 方法名 | 说明 | 参数 | 返回类型 |
|-------|------|------|----------|
| getAllArticles | 获取已发布文章列表 | params: PaginationParams可选 | Promise<ApiResponse<Article[]>> |
| getArticlesByStatus | 根据状态获取文章列表 | status: number0未发表 1已发表 2已删除 | Promise<ApiResponse<Article[]>> |
| getAllArticlesWithDeleted | 获取所有文章列表(包含已删除) | params: PaginationParams可选 | Promise<ApiResponse<Article[]>> |
| getArticleById | 根据ID获取文章详情 | articleid: number | Promise<ApiResponse<Article>> |
| getArticlesByAttributeId | 根据属性ID获取文章列表 | attributeid: number | Promise<ApiResponse<Article[]>> |
| getArticlesByTitle | 根据标题查询文章列表 | title: string | Promise<ApiResponse<Article[]>> |
| getPopularArticles | 获取热门文章 | 无 | Promise<ApiResponse<Article[]>> |
| createArticle | 创建文章 | articleData: ArticleDto | Promise<ApiResponse<Article>> |
| updateArticle | 更新文章 | articleid: number, articleData: ArticleDto | Promise<ApiResponse<Article>> |
| deleteArticle | 删除文章 | articleid: number | Promise<ApiResponse<boolean>> |
| getArticlesByCategory | 根据分类获取文章 | categoryid: number | Promise<ApiResponse<Article[]>> |
| incrementArticleViews | 增加文章浏览量 | articleid: number | Promise<ApiResponse<boolean>> |
| getLatestArticlesByAttribute | 根据属性ID获取最新文章 | attributeid: number | Promise<ApiResponse<Article[]>> |
| likeArticle | 点赞文章 | articleid: number | Promise<ApiResponse<boolean>> |
### 3. 分类服务 (categoryService.js)
提供分类的管理功能。
**主要方法**
| 方法名 | 说明 | 参数 | 返回类型 |
|-------|------|------|----------|
| getAllCategories | 获取所有分类 | 无 | Promise<ApiResponse<Category[]>> |
| getCategory | 获取指定分类 | typeid: number | Promise<ApiResponse<Category>> |
| createCategory | 创建新分类 | categoryData: CategoryDto | Promise<ApiResponse<Category>> |
| updateCategory | 更新分类 | typeid: number, categoryData: CategoryDto | Promise<ApiResponse<Category>> |
| deleteCategory | 删除分类 | typeid: number | Promise<ApiResponse<boolean>> |
### 4. 分类属性服务 (categoryAttributeService.js)
提供分类属性(标签)的管理功能。
**主要方法**
| 方法名 | 说明 | 参数 | 返回类型 |
|-------|------|------|----------|
| getAllAttributes | 获取所有分类属性 | 无 | Promise<ApiResponse<CategoryAttribute[]>> |
| getAttributeById | 根据ID获取分类属性 | attributeid: number | Promise<ApiResponse<CategoryAttribute>> |
| getAttributesByCategory | 根据分类ID获取属性列表 | categoryid: number | Promise<ApiResponse<CategoryAttribute[]>> |
| createAttribute | 创建分类属性 | attributeData: CategoryAttributeDto | Promise<ApiResponse<CategoryAttribute>> |
| updateAttribute | 更新分类属性 | attributeid: number, attributeData: CategoryAttributeDto | Promise<ApiResponse<CategoryAttribute>> |
| deleteAttribute | 删除分类属性 | attributeid: number | Promise<ApiResponse<boolean>> |
| checkAttributeExists | 检查分类下是否存在指定名称的属性 | categoryid: number, attributename: string | Promise<ApiResponse<boolean>> |
### 5. 用户认证服务 (loginService.js)
提供用户登录、注册和个人信息管理功能。
**主要方法**
| 方法名 | 说明 | 参数 | 返回类型 |
|-------|------|------|----------|
| login | 用户登录 | loginData: LoginDto | Promise<ApiResponse<User>> |
| register | 用户注册 | registerData: RegisterDto | Promise<ApiResponse<User>> |
| logout | 用户登出 | 无 | Promise<any> |
| getCurrentUser | 获取当前用户信息 | 无 | Promise<ApiResponse<User>> |
| updateUser | 更新用户信息 | userData: UserDto | Promise<ApiResponse<User>> |
| changePassword | 修改密码 | passwordData: ChangePasswordDto | Promise<ApiResponse<boolean>> |
### 6. 留言服务 (messageService.js)
提供留言的管理和查询功能。
**主要方法**
| 方法名 | 说明 | 参数 | 返回类型 |
|-------|------|------|----------|
| getAllMessages | 获取所有留言 | 无 | Promise<ApiResponse<Message[]>> |
| getMessageById | 获取单条留言 | messageid: number | Promise<ApiResponse<Message>> |
| getMessagesByArticleId | 根据文章ID获取留言 | articleid: number | Promise<ApiResponse<Message[]>> |
| getRootMessages | 获取根留言 | 无 | Promise<ApiResponse<Message[]>> |
| getRepliesByParentId | 根据父留言ID获取回复 | parentid: number | Promise<ApiResponse<Message[]>> |
| searchMessagesByNickname | 根据昵称搜索留言 | nickname: string | Promise<ApiResponse<Message[]>> |
| getMessageCountByArticleId | 获取文章评论数量 | articleid: number | Promise<ApiResponse<number>> |
| saveMessage | 创建留言 | messageData: MessageDto | Promise<ApiResponse<Message>> |
| deleteMessage | 删除留言 | messageid: number | Promise<ApiResponse<boolean>> |
| likeMessage | 点赞留言 | messageid: number | Promise<ApiResponse<boolean>> |
### 7. 疯言疯语服务 (nonsenseService.js)
提供疯言疯语内容的管理功能。
**主要方法**
| 方法名 | 说明 | 参数 | 返回类型 |
|-------|------|------|----------|
| getAllNonsense | 获取所有疯言疯语内容 | 无 | Promise<ApiResponse<Nonsense[]>> |
| getNonsenseByStatus | 根据状态获取疯言疯语内容 | status: number1:已发表, 0:草稿) | Promise<ApiResponse<Nonsense[]>> |
| saveNonsense | 保存疯言疯语内容 | nonsense: Nonsense | Promise<ApiResponse<Nonsense>> |
| deleteNonsense | 删除疯言疯语内容 | id: number | Promise<ApiResponse<boolean>> |
| updateNonsense | 更新疯言疯语内容 | nonsense: Nonsense | Promise<ApiResponse<Nonsense>> |
## 数据模型定义
### 1. 文章 (Article)
```typescript
interface Article {
articleid: number
title: string
content: string
attributeid: Number
categoryName: string
img?: string
createdAt: string
updatedAt: string
viewCount?: number
likes?: number
commentCount?: number
status?: number
markdownscontent: string
}
interface ArticleDto {
id?: number
title: string
content: string
attributeid: number
img?: string
status?: number
viewCount?: number
likes?: number
markdownscontent: string
}
```
### 2. 分类 (Category)
```typescript
interface Category {
typeid: number
typename: string
description?: string
createdAt?: string
updatedAt?: string
articleCount?: number
}
interface CategoryDto {
typename: string
description?: string
}
```
### 3. 分类属性 (CategoryAttribute)
```typescript
interface CategoryAttribute {
attributeid: number
categoryid: number
attributename: string
}
interface CategoryAttributeDto {
categoryid: number
attributename: string
}
```
### 4. 留言 (Message)
```typescript
interface Message {
messageid: number
content: string
nickname: string
email: string
articleid?: number
parentid?: number
createdAt: string
replyid?: number
likes?: number
messageimg?: string
}
interface MessageDto {
messageid?: number
nickname?: string
email?: string
content?: string
createdAt?: string
parentid?: number
replyid?: number
articleid?: number
messageimg?: string
}
```
### 5. 用户 (User)
```typescript
interface User {
id?: number
username?: string
password?: string
email?: string
phone?: string
role?: number
createTime?: string
avatar?: string
token?: string
}
interface UserDto {
username: string
password: string
email: string
phone: string
role?: number
}
```
### 6. 疯言疯语 (Nonsense)
```typescript
interface Nonsense {
nonsenseid: number
content: string
status?: number
time: string
}
interface NonsenseDto {
content: string
status?: number
time?: string
}
```
### 7. API响应 (ApiResponse)
```typescript
interface ApiResponse<T = any> {
success: boolean
code: number
message?: string
data?: T
total?: number
}
```
## API调用示例
### 导入服务
```javascript
import { articleService, categoryService, messageService, loginService } from '@/services'
```
### 文章相关调用示例
```javascript
// 获取文章列表
async function fetchArticles() {
try {
const response = await articleService.getAllArticles({ page: 1, size: 10 })
if (response.success) {
console.log('文章列表:', response.data)
} else {
console.error('获取文章列表失败:', response.message)
}
} catch (error) {
console.error('请求错误:', error)
}
}
// 创建新文章
async function createNewArticle() {
try {
const articleData = {
title: '新文章标题',
content: '文章内容',
attributeid: 1,
markdownscontent: '# 文章标题\n文章内容'
}
const response = await articleService.createArticle(articleData)
if (response.success) {
console.log('文章创建成功:', response.data)
}
} catch (error) {
console.error('创建文章失败:', error)
}
}
```
### 分类相关调用示例
```javascript
// 获取所有分类
async function fetchCategories() {
try {
const response = await categoryService.getAllCategories()
if (response.success) {
console.log('分类列表:', response.data)
}
} catch (error) {
console.error('获取分类失败:', error)
}
}
// 创建新分类
async function createCategory() {
try {
const categoryData = {
typename: '新技术',
description: '关于新技术的文章分类'
}
const response = await categoryService.createCategory(categoryData)
if (response.success) {
console.log('分类创建成功:', response.data)
}
} catch (error) {
console.error('创建分类失败:', error)
}
}
```
### 用户认证调用示例
```javascript
// 用户登录
async function userLogin() {
try {
const loginData = {
username: 'testuser',
password: 'password123'
}
const response = await loginService.login(loginData)
if (response.success) {
// 保存token
localStorage.setItem('token', response.data.token)
console.log('登录成功:', response.data)
}
} catch (error) {
console.error('登录失败:', error)
}
}
// 获取当前用户信息
async function getCurrentUserInfo() {
try {
const response = await loginService.getCurrentUser()
if (response.success) {
console.log('用户信息:', response.data)
}
} catch (error) {
console.error('获取用户信息失败:', error)
}
}
```
## 错误处理机制
前端API服务集成了统一的错误处理机制包括
1. **HTTP状态码处理**
- 401: 未授权自动清除token并跳转登录页
- 403: 拒绝访问
- 404: 请求资源不存在
- 500: 服务器错误
2. **请求错误处理**
- 网络连接错误
- 请求超时
- 服务器无响应
3. **错误信息提示**
- 所有错误通过Element Plus的ElMessage组件显示
- 支持自定义错误消息
## 开发指南
### 安装依赖
@@ -363,45 +468,14 @@ npm run preview
## 部署说明
1. 确保后端服务已部署并运行在正确的端口上
2. 修改前端API请求的基础URL指向实际的后端服务地址
2. 修改 `apiService.js`的基础URL指向实际的后端服务地址
3. 构建生产版本并部署到Web服务器
4. 配置Web服务器以支持单页应用路由 (SPA fallback)
## 注意事项
1. 项目使用了Element Plus和Ant Design Vue两个UI库请注意组件的正确引入和使用方式
2. 后端服务默认端口为8080前端开发服务器端口为3000
3. 确保CORS配置正确允许前端域名访问后端API
4. 对于需要认证的API需要在请求头中添加正确的认证信息
## 附录:数据模型
### 文章数据模型 (Article)
```javascript
{
articleid: Number, // 文章ID
title: String, // 文章标题
content: String, // 文章内容
author: String, // 作者
authorid: Number, // 作者ID
typeid: Number, // 分类ID
publishedAt: String, // 发布时间
viewCount: Number, // 浏览次数
status: Number, // 状态 (1表示已发布)
img: String // 文章图片
}
```
### 留言数据模型 (Message)
```javascript
{
id: Number, // 留言ID
nickname: String, // 昵称
email: String, // 邮箱
content: String, // 留言内容
time: String, // 留言时间
replies: Array // 回复列表
}
```
1. 所有API调用都应该使用services目录下导出的服务实例
2. 对于需要认证的操作确保用户已登录并持有有效的token
3. 在生产环境中确保修改API基础URL为实际的后端服务地址
4. 对于分页查询合理设置page和size参数以优化性能
5. 图片上传等大文件操作需要特别处理,避免超时