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:
754
README_API.md
754
README_API.md
@@ -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: number(0:未发表 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: number(1:已发表, 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. 图片上传等大文件操作需要特别处理,避免超时
|
||||
1415
package-lock.json
generated
1415
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -14,13 +14,9 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"@vicons/ionicons5": "^0.13.0",
|
||||
"ant-design-vue": "^4.2.6",
|
||||
"antd": "^5.27.3",
|
||||
"axios": "^1.12.2",
|
||||
"element-plus": "^2.11.5",
|
||||
"md-editor-v3": "^6.1.0",
|
||||
"naive-ui": "^2.43.1",
|
||||
"pinia": "^3.0.3",
|
||||
"sass": "^1.93.2",
|
||||
"undraw-ui": "^1.3.2",
|
||||
|
||||
@@ -257,7 +257,7 @@ const handleAttributeClick = (attribute: any) => {
|
||||
|
||||
globalStore.setValue('attribute', {
|
||||
id: attribute.attributeid,
|
||||
name: attribute.typename
|
||||
name: attribute.attributename
|
||||
})
|
||||
console.log(attribute)
|
||||
router.push({
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<el-row justify="center">
|
||||
<el-col :span="6" v-if="windowwidth">
|
||||
<div class="grid-content ep-bg-purple-dark">
|
||||
<div class="logo-text">清疯不颠</div>
|
||||
<div class="logo-text"> <a href="/">清疯不颠</a></div>
|
||||
</div>
|
||||
</el-col>
|
||||
<el-col :span="14" justify="center">
|
||||
@@ -31,16 +31,16 @@
|
||||
<!-- 搜索功能 -->
|
||||
<div class="search-wrapper">
|
||||
<button class="search-icon-btn" @click="toggleSearchBox" :class="{ 'active': isSearchBoxOpen }">
|
||||
<svg t="1761567058506" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5586" width="32" height="32"><path d="M512 858.3168c-194.816 0-352-166.2464-352-370.4832S317.184 117.3504 512 117.3504s352 166.2464 352 370.4832-157.184 370.4832-352 370.4832z m0-64c158.6688 0 288-136.8576 288-306.4832 0-169.6768-129.3312-306.4832-288-306.4832S224 318.1568 224 487.8336c0 169.6256 129.3312 306.4832 288 306.4832zM717.312 799.9488a32 32 0 0 1 46.4896-43.9808l91.4432 96.7168a32 32 0 0 1-46.4896 43.9808l-91.4432-96.768z" fill="#5A5A68" p-id="5587"></path></svg>
|
||||
<svg t="1761567058506" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
|
||||
p-id="5586" width="32" height="32">
|
||||
<path
|
||||
d="M512 858.3168c-194.816 0-352-166.2464-352-370.4832S317.184 117.3504 512 117.3504s352 166.2464 352 370.4832-157.184 370.4832-352 370.4832z m0-64c158.6688 0 288-136.8576 288-306.4832 0-169.6768-129.3312-306.4832-288-306.4832S224 318.1568 224 487.8336c0 169.6256 129.3312 306.4832 288 306.4832zM717.312 799.9488a32 32 0 0 1 46.4896-43.9808l91.4432 96.7168a32 32 0 0 1-46.4896 43.9808l-91.4432-96.768z"
|
||||
fill="#5A5A68" p-id="5587"></path>
|
||||
</svg>
|
||||
</button>
|
||||
<div class="search-box-container" :class="{ 'open': isSearchBoxOpen }">
|
||||
<el-input
|
||||
v-model="searchKeyword"
|
||||
placeholder="回车搜索文章..."
|
||||
class="search-input"
|
||||
@keyup.enter="performSearch"
|
||||
@blur="closeSearchBoxWithDelay"
|
||||
/>
|
||||
<el-input v-model="searchKeyword" placeholder="回车搜索文章..." class="search-input" @keyup.enter="performSearch"
|
||||
@blur="closeSearchBoxWithDelay" />
|
||||
</div>
|
||||
</div>
|
||||
</el-col>
|
||||
@@ -56,67 +56,59 @@
|
||||
<div id="content-section" :class="{ 'visible': isconts }">
|
||||
<div class="nonsensetitle" v-if="classnonsenset">
|
||||
<div class="nonsensetitleconst">
|
||||
<h1>{{Cardtitle}}</h1>
|
||||
<h1>{{ Cardtitle }}</h1>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 左侧模块 -->
|
||||
<div class="leftmodluecontainer" v-if="isleftmodluecontainer">
|
||||
<LeftModule class="leftmodluepage" :class="{ 'nonsensetmargintop': classmoduleorrouter}" v-if="windowwidth" />
|
||||
</div>
|
||||
<div class="leftmodluecontainer" v-if="isleftmodluecontainer">
|
||||
<LeftModule class="leftmodluepage" :class="{ 'nonsensetmargintop': classmoduleorrouter }" v-if="windowwidth" />
|
||||
</div>
|
||||
|
||||
<!-- 内容模块 -->
|
||||
<RouterView class="RouterViewpage" :class="{'forbidwidth': !isleftmodluecontainer, 'nonsensetmargintop': classmoduleorrouter }" />
|
||||
<RouterView class="RouterViewpage"
|
||||
:class="{ 'forbidwidth': !isleftmodluecontainer, 'nonsensetmargintop': classmoduleorrouter }" />
|
||||
</div>
|
||||
|
||||
<!-- 分页区域 -->
|
||||
<div class="Pagination">
|
||||
<!-- 分页组件可以在这里添加 -->
|
||||
</div>
|
||||
<Establish class="establish-container" v-if="Login" />
|
||||
<Establish class="establish-container" v-if="Login" />
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { ref, onMounted, onUnmounted, watch, computed } from 'vue';
|
||||
import { useRouter, useRoute } from 'vue-router';
|
||||
import LeftModule from '@/components/LeftModule.vue';
|
||||
import Establish from '@/layouts/establish.vue'
|
||||
import Establish from '@/layouts/establish.vue';
|
||||
|
||||
// ========== 组件初始化 ==========
|
||||
|
||||
// 路由相关
|
||||
const router = useRouter();
|
||||
const route = useRoute();
|
||||
|
||||
// 全局状态管理
|
||||
import { useGlobalStore } from '@/store/globalStore'
|
||||
import { useGlobalStore } from '@/store/globalStore';
|
||||
const globalStore = useGlobalStore();
|
||||
const Login = computed(() => globalStore.Login);
|
||||
|
||||
const globalStore = useGlobalStore()
|
||||
const Login = computed(() => globalStore.Login)
|
||||
// ========== 响应式状态定义 ==========
|
||||
|
||||
// 响应式状态
|
||||
// 文章标题,用于显示在页面上的标题内容
|
||||
// 页面标题和样式相关状态
|
||||
const Cardtitle = ref('');
|
||||
// 控制模块或路由相关的CSS类名
|
||||
const classmoduleorrouter = ref(false);
|
||||
|
||||
// 控制左侧模块容器是否显示
|
||||
const isleftmodluecontainer = ref(true);
|
||||
|
||||
// 控制hero区域的CSS类名
|
||||
const classnonsenset = ref(false);
|
||||
const classhero = ref(false);
|
||||
|
||||
// 控制内容区域是否可见
|
||||
const isconts = ref(false);
|
||||
|
||||
// 控制左侧模块是否处于滚动状态
|
||||
const isScrollingleftmodlue = ref(false);
|
||||
// 顶部导航栏的样式状态(transparent/solid/hide)
|
||||
const elrowtop = ref('transparent');
|
||||
|
||||
// 控制疯言疯语页面标题区域的显示
|
||||
const classnonsenset = ref(false);
|
||||
// 判断窗口是否为宽屏(大于768px)
|
||||
// 布局相关状态
|
||||
const isleftmodluecontainer = ref(true);
|
||||
const isconts = ref(false);
|
||||
const isScrollingleftmodlue = ref(false);
|
||||
const windowwidth = ref(true);
|
||||
const activeIndex = ref('home');
|
||||
const localhome= 'home';
|
||||
|
||||
// 导航相关状态
|
||||
const activeIndex = ref('home');
|
||||
const localhome = 'home';
|
||||
let rpsliturl = route.path.split('/');
|
||||
|
||||
// 搜索相关状态
|
||||
@@ -130,33 +122,130 @@ const heroText = ref('');
|
||||
let heroIndex = 0;
|
||||
let heroTimer: number | undefined;
|
||||
|
||||
// ========== 打字机效果模块 ==========
|
||||
|
||||
/**
|
||||
* 打字机效果函数
|
||||
* 初始化并启动打字机效果
|
||||
* @param {string} text - 要显示的完整文本
|
||||
*/
|
||||
const startTypewriter = () => {
|
||||
// 重置状态
|
||||
heroText.value = '';
|
||||
heroIndex = 0;
|
||||
if (heroTimer) clearInterval(heroTimer);
|
||||
|
||||
// 清除可能存在的定时器
|
||||
if (heroTimer) {
|
||||
clearInterval(heroTimer);
|
||||
}
|
||||
|
||||
// 设置新的定时器,逐字显示文本
|
||||
heroTimer = window.setInterval(() => {
|
||||
if (heroIndex < fullHeroText.length) {
|
||||
heroText.value += fullHeroText[heroIndex];
|
||||
heroIndex++;
|
||||
} else {
|
||||
// 文本显示完毕,清除定时器
|
||||
clearInterval(heroTimer);
|
||||
}
|
||||
}, 100);
|
||||
};
|
||||
|
||||
/**
|
||||
* 菜单选择跳转
|
||||
* 停止打字机效果并显示完整文本
|
||||
*/
|
||||
const stopTypewriter = () => {
|
||||
// 清除定时器
|
||||
if (heroTimer) {
|
||||
clearInterval(heroTimer);
|
||||
}
|
||||
// 直接显示完整文本
|
||||
heroText.value = fullHeroText;
|
||||
};
|
||||
|
||||
// ========== 导航和路由处理模块 ==========
|
||||
|
||||
/**
|
||||
* 处理菜单选择并跳转到对应路由
|
||||
* @param {string} key - 菜单项的key值,对应路由路径
|
||||
*/
|
||||
const handleSelect = (key: string) => {
|
||||
// globalStore.clearAll()
|
||||
router.push({ path: '/' + key });
|
||||
};
|
||||
|
||||
/**
|
||||
* 切换搜索框显示/隐藏
|
||||
* 设置当前激活的菜单项并存储路径信息
|
||||
* @param {string} path - 当前路由路径
|
||||
*/
|
||||
const setActiveIndex = (path: string) => {
|
||||
// 存储当前路径到全局状态
|
||||
globalStore.setValue('localpath', {
|
||||
name: path
|
||||
});
|
||||
|
||||
// 特殊处理消息页面,清除文章信息
|
||||
if (path === 'message') {
|
||||
globalStore.removeValue('articleInfo');
|
||||
}
|
||||
|
||||
// 更新激活菜单项
|
||||
activeIndex.value = path;
|
||||
};
|
||||
|
||||
/**
|
||||
* 根据路由路径设置页面状态
|
||||
*/
|
||||
const updatePageState = () => {
|
||||
// 根据是否为主页根路径设置hero区域状态
|
||||
classhero.value = !(rpsliturl[1] == localhome && rpsliturl[2] == undefined);
|
||||
|
||||
// 控制左侧模块容器的显示/隐藏
|
||||
isleftmodluecontainer.value = rpsliturl[1] !== "articlesave";
|
||||
};
|
||||
|
||||
/**
|
||||
* 更新文章标题和相关显示状态
|
||||
*/
|
||||
const updateArticleTitle = () => {
|
||||
let articledata: any = null;
|
||||
|
||||
// 根据不同路由参数获取文章标题数据
|
||||
if (rpsliturl[2] === 'aericletype') {
|
||||
// 按属性类型获取
|
||||
articledata = globalStore.getValue('attribute')?.name;
|
||||
console.log('attributeId参数:', articledata);
|
||||
}
|
||||
else if (rpsliturl[2] === 'aericletitle') {
|
||||
// 按标题搜索获取
|
||||
articledata = globalStore.getValue('title')?.name;
|
||||
}
|
||||
else if (rpsliturl[1] === 'nonsense') {
|
||||
// 疯言疯语页面特殊处理
|
||||
articledata = "疯言疯语";
|
||||
}
|
||||
|
||||
// 确定标题区域的显示状态
|
||||
const shouldHideTitle =
|
||||
// 特殊页面不需要显示标题
|
||||
(rpsliturl[1] === 'article-list' ||
|
||||
rpsliturl[1] === 'message' ||
|
||||
rpsliturl[1] === 'about') ||
|
||||
// 在主页且无标题数据时,不显示标题
|
||||
(rpsliturl[1] === localhome && !articledata);
|
||||
|
||||
// 更新标题显示状态
|
||||
classnonsenset.value = !shouldHideTitle && !!articledata;
|
||||
classmoduleorrouter.value = !shouldHideTitle && !!articledata;
|
||||
|
||||
// 设置标题内容
|
||||
if (articledata) {
|
||||
Cardtitle.value = articledata;
|
||||
}
|
||||
};
|
||||
|
||||
// ========== 搜索功能模块 ==========
|
||||
|
||||
/**
|
||||
* 切换搜索框的显示/隐藏状态
|
||||
*/
|
||||
const toggleSearchBox = () => {
|
||||
isSearchBoxOpen.value = !isSearchBoxOpen.value;
|
||||
@@ -168,20 +257,23 @@ const toggleSearchBox = () => {
|
||||
};
|
||||
|
||||
/**
|
||||
* 关闭搜索框
|
||||
* 立即关闭搜索框
|
||||
*/
|
||||
const closeSearchBox = () => {
|
||||
isSearchBoxOpen.value = false;
|
||||
};
|
||||
|
||||
/**
|
||||
* 带延迟关闭搜索框(处理点击搜索按钮后的情况)
|
||||
* 带延迟关闭搜索框
|
||||
* 用于处理点击搜索按钮后的情况,让用户有时间看到反馈
|
||||
*/
|
||||
const closeSearchBoxWithDelay = () => {
|
||||
// 清除可能存在的定时器
|
||||
if (searchCloseTimer) {
|
||||
clearTimeout(searchCloseTimer);
|
||||
}
|
||||
|
||||
// 设置新的延迟关闭定时器
|
||||
searchCloseTimer = window.setTimeout(() => {
|
||||
isSearchBoxOpen.value = false;
|
||||
}, 300);
|
||||
@@ -189,15 +281,18 @@ const closeSearchBoxWithDelay = () => {
|
||||
|
||||
/**
|
||||
* 执行搜索操作
|
||||
* 将搜索关键词存储到全局状态并跳转到搜索结果页面
|
||||
*/
|
||||
const performSearch = () => {
|
||||
// 验证搜索关键词不为空
|
||||
if (searchKeyword.value.trim()) {
|
||||
// 这里可以根据实际需求实现搜索逻辑
|
||||
// 存储文章信息到全局状态
|
||||
globalStore.setValue('articleserarch', {
|
||||
name: searchKeyword.value
|
||||
})
|
||||
router.push({ path: `/home/aericletitle`});
|
||||
// 存储搜索关键词到全局状态
|
||||
globalStore.setValue('articleserarch', {
|
||||
name: searchKeyword.value
|
||||
});
|
||||
|
||||
// 跳转到搜索结果页面
|
||||
router.push({ path: `/home/aericletitle` });
|
||||
}
|
||||
|
||||
// 搜索后保持搜索框打开状态
|
||||
@@ -206,154 +301,140 @@ const performSearch = () => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 根据路由路径设置页面状态
|
||||
*/
|
||||
const updatePageState = () => {
|
||||
if (rpsliturl[1] == localhome && rpsliturl[2] == undefined) {
|
||||
classhero.value = false;
|
||||
} else {
|
||||
classhero.value = true;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 设置当前激活的菜单项
|
||||
*/
|
||||
const setActiveIndex = (path: string) => {
|
||||
// 存储文章信息到全局状态
|
||||
globalStore.setValue('localpath', {
|
||||
name: path
|
||||
})
|
||||
if (path === 'message') {
|
||||
globalStore.removeValue('articleInfo')
|
||||
}
|
||||
activeIndex.value =path;
|
||||
};
|
||||
|
||||
|
||||
// ========== 响应式处理模块 ==========
|
||||
|
||||
/**
|
||||
* 处理窗口大小变化
|
||||
* 根据屏幕宽度调整布局和内容显示
|
||||
*/
|
||||
const handleResize = () => {
|
||||
// 更新窗口宽度状态
|
||||
windowwidth.value = window.innerWidth > 768;
|
||||
|
||||
// 根据屏幕大小调整内容区可见性
|
||||
// 首页特殊处理:小屏幕下默认显示内容区
|
||||
if (rpsliturl[1] === localhome) {
|
||||
isconts.value = window.innerWidth <= 768 ? true : false;
|
||||
isconts.value = window.innerWidth <= 768;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 处理滚动事件
|
||||
* 处理页面滚动事件
|
||||
* 根据滚动位置调整导航栏样式和内容显示动画
|
||||
*/
|
||||
const handleScroll = () => {
|
||||
// 屏幕小于768时只切换导航栏样式,不做内容动画
|
||||
// 小屏幕设备只切换导航栏样式
|
||||
if (window.innerWidth < 768) {
|
||||
elrowtop.value = window.scrollY > 100 ? 'solid' : 'transparent';
|
||||
updateNavbarStyle(window.scrollY);
|
||||
return;
|
||||
}
|
||||
|
||||
// 导航栏样式切换
|
||||
if (window.scrollY > 1200) {
|
||||
elrowtop.value = 'hide';
|
||||
} else {
|
||||
elrowtop.value = window.scrollY > 100 ? 'solid' : 'transparent';
|
||||
}
|
||||
// 首页内容区滚动动画
|
||||
// 大屏幕设备完整处理
|
||||
updateNavbarStyle(window.scrollY);
|
||||
|
||||
// 仅在首页根路径应用滚动动画
|
||||
if (rpsliturl[1] === localhome && rpsliturl[2] == undefined) {
|
||||
// 控制内容区和左侧模块的滚动状态
|
||||
isconts.value = window.scrollY > 200;
|
||||
isScrollingleftmodlue.value = window.scrollY > 600;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 更新文章标题和相关状态
|
||||
* 根据滚动位置更新导航栏样式
|
||||
* @param {number} scrollY - 当前滚动位置
|
||||
*/
|
||||
const updateArticleTitle = () => {
|
||||
let articledata: any = null;
|
||||
const updateNavbarStyle = (scrollY: number) => {
|
||||
// 根据滚动位置设置导航栏样式
|
||||
if (scrollY > 1200) {
|
||||
elrowtop.value = 'hide'; // 隐藏导航栏
|
||||
} else {
|
||||
elrowtop.value = scrollY > 100 ? 'solid' : 'transparent'; // 固定或透明样式
|
||||
}
|
||||
};
|
||||
|
||||
// 优先使用attributeId参数(新接口)
|
||||
if (rpsliturl[2] === 'aericletype') {
|
||||
articledata = globalStore.getValue('attribute')?.name;
|
||||
}
|
||||
// 搜索标题
|
||||
else if (rpsliturl[2] === 'aericletitle') {
|
||||
articledata = globalStore.getValue('title')?.name;
|
||||
}
|
||||
// 疯言疯语页面
|
||||
else if (rpsliturl[1] === 'nonsense') {
|
||||
articledata = "疯言疯语";
|
||||
}
|
||||
// ========== 路由监听和页面初始化 ==========
|
||||
|
||||
// 特殊页面不需要显示标题
|
||||
if (rpsliturl[1] === 'article-list' || rpsliturl[1] === 'message' || rpsliturl[1] === 'about') {
|
||||
classnonsenset.value = false;
|
||||
classmoduleorrouter.value = false;
|
||||
}
|
||||
// 在主页且articledata为空时,不显示标题
|
||||
else if (rpsliturl[1] === localhome && !articledata) {
|
||||
classnonsenset.value = false;
|
||||
classmoduleorrouter.value = false;
|
||||
}
|
||||
/**
|
||||
* 处理路由变化的核心函数
|
||||
* 更新页面状态、标题、激活菜单项等
|
||||
*/
|
||||
const handleRouteChange = () => {
|
||||
// 重新解析路由路径
|
||||
rpsliturl = route.path.split('/');
|
||||
|
||||
// 显示文章标题
|
||||
else if (articledata) {
|
||||
Cardtitle.value = articledata;
|
||||
classnonsenset.value = true;
|
||||
classmoduleorrouter.value = true;
|
||||
// 更新页面相关状态
|
||||
updatePageState();
|
||||
setActiveIndex(rpsliturl[1]);
|
||||
updateArticleTitle();
|
||||
|
||||
// 页面跳转后回到顶部
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
|
||||
// 根据是否为首页决定是否启动打字机效果
|
||||
if (rpsliturl[1] === localhome && rpsliturl[2] == undefined) {
|
||||
// 首页启动打字机效果
|
||||
startTypewriter();
|
||||
} else {
|
||||
// 非首页直接显示完整文本
|
||||
isconts.value = true;
|
||||
stopTypewriter();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 监听路由变化
|
||||
* 初始化页面
|
||||
*/
|
||||
watch(() => route.path, () => {
|
||||
rpsliturl = route.path.split('/');
|
||||
updatePageState();
|
||||
setActiveIndex(rpsliturl[1]);
|
||||
updateArticleTitle();
|
||||
// 跳转后回到顶部
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
// 首页内容区滚动动画仅大屏下生效
|
||||
const initializePage = () => {
|
||||
// 初始化窗口大小
|
||||
handleResize();
|
||||
// 启动打字机效果(如果是首页)
|
||||
if (rpsliturl[1] === localhome && rpsliturl[2] == undefined) {
|
||||
// 首页时启动打字机效果
|
||||
startTypewriter();
|
||||
} else {
|
||||
isconts.value = true;
|
||||
heroText.value =fullHeroText;
|
||||
if (heroTimer) clearInterval(heroTimer);
|
||||
}
|
||||
// 非首页时关闭左侧状态栏
|
||||
if (rpsliturl[1] == "articlesave") {
|
||||
isleftmodluecontainer.value = false;
|
||||
} else {
|
||||
isleftmodluecontainer.value = true;
|
||||
}
|
||||
}, { immediate: true });
|
||||
};
|
||||
|
||||
// ========== 生命周期钩子 ==========
|
||||
|
||||
/**
|
||||
* 生命周期钩子
|
||||
* 组件挂载时执行
|
||||
*/
|
||||
onMounted(() => {
|
||||
// 初始化窗口大小
|
||||
// 初始化页面
|
||||
initializePage();
|
||||
|
||||
|
||||
handleResize();
|
||||
// 添加事件监听器
|
||||
window.addEventListener('resize', handleResize);
|
||||
window.addEventListener('scroll', handleScroll);
|
||||
});
|
||||
|
||||
/**
|
||||
* 组件卸载时执行
|
||||
*/
|
||||
onUnmounted(() => {
|
||||
// 清理事件监听器
|
||||
window.removeEventListener('resize', handleResize);
|
||||
window.removeEventListener('scroll', handleScroll);
|
||||
|
||||
// 清理定时器
|
||||
if (heroTimer) clearInterval(heroTimer);
|
||||
if (heroTimer) {
|
||||
clearInterval(heroTimer);
|
||||
}
|
||||
if (searchCloseTimer) {
|
||||
clearTimeout(searchCloseTimer);
|
||||
}
|
||||
});
|
||||
|
||||
// ========== 监听器 ==========
|
||||
|
||||
/**
|
||||
* 监听路由变化
|
||||
* 当路由变化时更新页面状态
|
||||
*/
|
||||
watch(
|
||||
() => route.path,
|
||||
handleRouteChange,
|
||||
{ immediate: true } // 立即执行一次,确保初始状态正确
|
||||
);
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
@@ -402,9 +483,11 @@ onUnmounted(() => {
|
||||
width: 100%;
|
||||
opacity: 1;
|
||||
}
|
||||
.el-input__wrapper{
|
||||
|
||||
.el-input__wrapper {
|
||||
width: 80px;
|
||||
}
|
||||
|
||||
.search-input {
|
||||
border: none;
|
||||
outline: none;
|
||||
|
||||
@@ -39,46 +39,76 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
// 组件导入和初始化
|
||||
import { ref, onMounted, onBeforeUnmount } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
import { articleService, messageService, categoryAttributeService, nonsenseService, categoryService, loginService } from '@/services'
|
||||
import { articleService, categoryAttributeService, nonsenseService, categoryService, loginService } from '@/services'
|
||||
|
||||
// 全局状态管理
|
||||
import { useGlobalStore } from '@/store/globalStore'
|
||||
const globalStore = useGlobalStore()
|
||||
// 路由参数
|
||||
const router = useRouter()
|
||||
// 分类列表
|
||||
|
||||
// ==============================
|
||||
// 状态管理模块
|
||||
// ==============================
|
||||
/**
|
||||
* 按钮展开状态
|
||||
* @type {import('vue').Ref<boolean>}
|
||||
*/
|
||||
const isExpanded = ref(false)
|
||||
|
||||
/**
|
||||
* 分类列表
|
||||
* @type {import('vue').Ref<Array<{value: string, label: string}>>}
|
||||
*/
|
||||
const categories = ref([])
|
||||
//蒙版
|
||||
|
||||
/**
|
||||
* 标签模态框显示状态
|
||||
* @type {import('vue').Ref<boolean>}
|
||||
*/
|
||||
const showAttributeModal = ref(false)
|
||||
// 选中的分类和新标签
|
||||
|
||||
/**
|
||||
* 疯言疯语模态框显示状态
|
||||
* @type {import('vue').Ref<boolean>}
|
||||
*/
|
||||
const isNonsenseModalVisible = ref(false)
|
||||
|
||||
/**
|
||||
* 疯言疯语内容
|
||||
* @type {import('vue').Ref<string>}
|
||||
*/
|
||||
const nonsenseContent = ref('')
|
||||
|
||||
/**
|
||||
* 标签数据传输对象
|
||||
* @type {import('vue').Ref<{categoryid: string, name: string}>}
|
||||
*/
|
||||
const CategoryAttributeDto = ref({
|
||||
categoryid: '',
|
||||
name: ''
|
||||
})
|
||||
// 定义响应式状态
|
||||
const isExpanded = ref(false)
|
||||
// 疯言疯语模态框状态
|
||||
const isNonsenseModalVisible = ref(false)
|
||||
const nonsenseContent = ref('')
|
||||
// 显示标签蒙板
|
||||
const showAttributes = () => {
|
||||
showAttributeModal.value = true
|
||||
}
|
||||
const closeAttributeModal = () => {
|
||||
showAttributeModal.value = false
|
||||
}
|
||||
|
||||
// ==============================
|
||||
// 按钮配置和管理模块
|
||||
// ==============================
|
||||
|
||||
// 基础按钮配置
|
||||
/**
|
||||
* 基础按钮配置
|
||||
* @type {Array<{id: string, label: string, icon: string}>}
|
||||
*/
|
||||
const baseButtons = [
|
||||
{ id: 'logout', label: '登出', icon: 'icon-logout' },
|
||||
{ id: 'reload', label: '刷新', icon: 'icon-reload' }
|
||||
|
||||
]
|
||||
|
||||
// 页面特定按钮配置
|
||||
/**
|
||||
* 页面特定按钮配置映射
|
||||
* @type {Object.<string, Array<{id: string, label: string, icon: string}>>}
|
||||
*/
|
||||
const pageButtons = {
|
||||
// 文章详情页按钮
|
||||
article: [
|
||||
@@ -124,23 +154,11 @@ const pageButtons = {
|
||||
// 默认按钮
|
||||
default: baseButtons
|
||||
}
|
||||
// 根据status状态获取按钮配置
|
||||
const getButtonsByStatus = (status) => {
|
||||
globalStore.removeValue('articlestatus')
|
||||
globalStore.setValue('articlestatus', {
|
||||
status: status
|
||||
})
|
||||
//跳转文章列表页面,添加时间戳参数确保页面刷新
|
||||
try {
|
||||
// 添加时间戳作为查询参数,确保页面强制刷新
|
||||
const timestamp = new Date().getTime();
|
||||
router.push({ path: `/home/aericlestatus`, query: { t: timestamp } })
|
||||
} catch (error) {
|
||||
console.error('页面跳转失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
// 根据当前页面返回对应的按钮配置
|
||||
/**
|
||||
* 根据当前页面返回对应的按钮配置
|
||||
* @returns {Array<{id: string, label: string, icon: string}>} 按钮配置数组
|
||||
*/
|
||||
const isbuttonsave = () => {
|
||||
try {
|
||||
// 获取当前页面路径名称
|
||||
@@ -152,15 +170,60 @@ const isbuttonsave = () => {
|
||||
return pageButtons.default;
|
||||
}
|
||||
}
|
||||
// 切换按钮显示状态
|
||||
|
||||
/**
|
||||
* 切换按钮展开/收起状态
|
||||
* @param {Event} event - 点击事件对象
|
||||
*/
|
||||
const toggleExpand = (event) => {
|
||||
isExpanded.value = !isExpanded.value
|
||||
// 防止点击弹出的按钮后再次触发主按钮的点击事件
|
||||
event.stopPropagation()
|
||||
|
||||
}
|
||||
|
||||
// 显示疯言疯语模态框
|
||||
/**
|
||||
* 为每个按钮计算动态样式
|
||||
* @param {number} index - 按钮索引
|
||||
* @returns {Object} CSS样式对象
|
||||
*/
|
||||
const getButtonStyle = (index) => {
|
||||
// 计算过渡时间,确保显示时从上到下逐渐出现,隐藏时从下到上逐渐消失
|
||||
const showDelay = Math.max(0.1, 0.2 + index * 0.2);
|
||||
const hideDelay = 0.3 + index * 0.2;
|
||||
|
||||
// 根据是否展开返回不同的过渡样式
|
||||
if (isExpanded.value) {
|
||||
return {
|
||||
transition: `all ${showDelay}s ease-in-out`
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
transition: `all ${hideDelay}s ease-in-out`
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// ==============================
|
||||
// 模态框管理模块
|
||||
// ==============================
|
||||
|
||||
/**
|
||||
* 显示标签模态框
|
||||
*/
|
||||
const showAttributes = () => {
|
||||
showAttributeModal.value = true
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭标签模态框
|
||||
*/
|
||||
const closeAttributeModal = () => {
|
||||
showAttributeModal.value = false
|
||||
}
|
||||
|
||||
/**
|
||||
* 显示疯言疯语模态框
|
||||
*/
|
||||
const showNonsenseModal = () => {
|
||||
nonsenseContent.value = '' // 清空输入框
|
||||
isNonsenseModalVisible.value = true
|
||||
@@ -180,7 +243,43 @@ const showNonsenseModal = () => {
|
||||
})
|
||||
}
|
||||
|
||||
// 保存疯言疯语
|
||||
// ==============================
|
||||
// 功能操作方法模块
|
||||
// ==============================
|
||||
|
||||
/**
|
||||
* 处理错误响应的工具函数
|
||||
* @param {Error} error - 错误对象
|
||||
* @param {string} defaultMessage - 默认错误消息
|
||||
*/
|
||||
const handleErrorResponse = (error, defaultMessage = '操作失败') => {
|
||||
console.error('操作失败:', error)
|
||||
ElMessage.error(error.message || defaultMessage)
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据文章状态获取并跳转文章列表
|
||||
* @param {number} status - 文章状态 0:未发表 1:已发表 2:已删除
|
||||
*/
|
||||
const getButtonsByStatus = (status) => {
|
||||
globalStore.removeValue('articlestatus')
|
||||
globalStore.setValue('articlestatus', {
|
||||
status: status
|
||||
})
|
||||
|
||||
// 跳转文章列表页面,添加时间戳参数确保页面刷新
|
||||
try {
|
||||
const timestamp = new Date().getTime();
|
||||
router.push({ path: `/home/aericlestatus`, query: { t: timestamp } })
|
||||
} catch (error) {
|
||||
console.error('页面跳转失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存疯言疯语
|
||||
* @param {string} content - 疯言疯语内容
|
||||
*/
|
||||
const saveNonsense = (content) => {
|
||||
if (!content || content.trim() === '') {
|
||||
ElMessage.warning('内容不能为空')
|
||||
@@ -199,12 +298,10 @@ const saveNonsense = (content) => {
|
||||
}
|
||||
}).catch(err => handleErrorResponse(err, '发布失败'))
|
||||
}
|
||||
// 处理错误响应的工具函数
|
||||
const handleErrorResponse = (error, defaultMessage = '操作失败') => {
|
||||
console.error('操作失败:', error)
|
||||
ElMessage.error(error.message || defaultMessage)
|
||||
}
|
||||
// 新建分类
|
||||
|
||||
/**
|
||||
* 新建分类
|
||||
*/
|
||||
const createCategory = () => {
|
||||
ElMessageBox.prompt('请输入分类名称:', '新建分类', {
|
||||
confirmButtonText: '保存',
|
||||
@@ -230,7 +327,10 @@ const createCategory = () => {
|
||||
});
|
||||
};
|
||||
|
||||
// 保存分类
|
||||
/**
|
||||
* 保存分类
|
||||
* @param {string} typename - 分类名称
|
||||
*/
|
||||
const saveCategory = (typename) => {
|
||||
categoryService.saveCategory({
|
||||
typename: typename
|
||||
@@ -245,7 +345,10 @@ const saveCategory = (typename) => {
|
||||
}
|
||||
}).catch(err => handleErrorResponse(err, '创建分类失败'));
|
||||
};
|
||||
// createAttribute新建标签
|
||||
|
||||
/**
|
||||
* 新建标签
|
||||
*/
|
||||
const createAttribute = async () => {
|
||||
showAttributes()
|
||||
try {
|
||||
@@ -263,14 +366,19 @@ const createAttribute = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
const saveAttribute = (CategoryAttributeDto) => {
|
||||
if (!CategoryAttributeDto.categoryid || !CategoryAttributeDto.name) {
|
||||
/**
|
||||
* 保存标签
|
||||
* @param {{categoryid: string, name: string}} dto - 标签数据传输对象
|
||||
*/
|
||||
const saveAttribute = (dto) => {
|
||||
if (!dto.categoryid || !dto.name) {
|
||||
ElMessage.warning('请选择分类和输入标签名称')
|
||||
return
|
||||
}
|
||||
|
||||
categoryAttributeService.createAttribute({
|
||||
categoryid: Number(CategoryAttributeDto.categoryid),
|
||||
attributename: CategoryAttributeDto.name
|
||||
categoryid: Number(dto.categoryid),
|
||||
attributename: dto.name
|
||||
}).then(response => {
|
||||
if (response.code === 200) {
|
||||
closeAttributeModal()
|
||||
@@ -283,13 +391,16 @@ const saveAttribute = (CategoryAttributeDto) => {
|
||||
}).catch(err => handleErrorResponse(err, '创建标签失败'));
|
||||
};
|
||||
|
||||
// 删除文章方法
|
||||
/**
|
||||
* 删除文章
|
||||
*/
|
||||
const deleteArticle = () => {
|
||||
const articleId = globalStore.getValue('articleInfo')?.id
|
||||
const articleId = globalStore.getValue('articleInfo')?.articleid
|
||||
if (!articleId) {
|
||||
ElMessage.warning('缺少文章ID参数')
|
||||
return
|
||||
}
|
||||
|
||||
// 确认删除
|
||||
ElMessageBox.confirm('确定删除该文章吗?', '删除确认', {
|
||||
confirmButtonText: '确定',
|
||||
@@ -312,13 +423,17 @@ const deleteArticle = () => {
|
||||
// 取消删除,静默处理
|
||||
})
|
||||
}
|
||||
// 修改文章方法
|
||||
|
||||
/**
|
||||
* 修改文章
|
||||
*/
|
||||
const updateArticle = () => {
|
||||
const articleId = globalStore.getValue('articleInfo')
|
||||
if (!articleId) {
|
||||
ElMessage.warning('缺少文章参数')
|
||||
return
|
||||
}
|
||||
|
||||
// 确认修改
|
||||
ElMessageBox.confirm('确定修改该文章吗?', '修改确认', {
|
||||
confirmButtonText: '确定',
|
||||
@@ -332,7 +447,9 @@ const updateArticle = () => {
|
||||
})
|
||||
}
|
||||
|
||||
// 登出方法
|
||||
/**
|
||||
* 登出系统
|
||||
*/
|
||||
const logout = () => {
|
||||
// 调用登出接口
|
||||
loginService.logout()
|
||||
@@ -351,12 +468,22 @@ const logout = () => {
|
||||
})
|
||||
.catch(err => handleErrorResponse(err, '登出失败'))
|
||||
}
|
||||
// 刷新页面
|
||||
|
||||
/**
|
||||
* 刷新页面
|
||||
*/
|
||||
const reloadPage = () => {
|
||||
globalStore.clearAll()
|
||||
|
||||
}
|
||||
// 处理按钮点击事件
|
||||
|
||||
// ==============================
|
||||
// 事件处理模块
|
||||
// ==============================
|
||||
|
||||
/**
|
||||
* 处理按钮点击事件
|
||||
* @param {{id: string, label: string, icon: string}} button - 按钮对象
|
||||
*/
|
||||
const handleButtonClick = (button) => {
|
||||
console.log('点击了按钮:', button.id, button.label)
|
||||
|
||||
@@ -364,20 +491,15 @@ const handleButtonClick = (button) => {
|
||||
switch (button.id) {
|
||||
// 新增操作
|
||||
case 'create-article':
|
||||
// 清除更新文章状态
|
||||
router.push({ path: '/articlesave' })
|
||||
break
|
||||
|
||||
case 'create-category':
|
||||
createCategory()
|
||||
break
|
||||
|
||||
case 'create-tag':
|
||||
createAttribute()
|
||||
break
|
||||
|
||||
case 'create-nonsense':
|
||||
// 显示疯言疯语模态框
|
||||
showNonsenseModal()
|
||||
break
|
||||
|
||||
@@ -395,24 +517,20 @@ const handleButtonClick = (button) => {
|
||||
case 'del-articles':
|
||||
getButtonsByStatus(2)
|
||||
break
|
||||
|
||||
case 'unpublished-articles':
|
||||
getButtonsByStatus(0)
|
||||
break
|
||||
|
||||
case 'published-articles':
|
||||
getButtonsByStatus(1)
|
||||
break
|
||||
|
||||
case 'view-articles':
|
||||
router.push({ path: '/home' })
|
||||
break
|
||||
|
||||
// 登出操作
|
||||
// 系统操作
|
||||
case 'logout':
|
||||
logout();
|
||||
break
|
||||
|
||||
case 'reload':
|
||||
reloadPage()
|
||||
break
|
||||
@@ -422,32 +540,14 @@ const handleButtonClick = (button) => {
|
||||
ElMessage.info(`功能 ${button.label} 暂未实现`)
|
||||
}
|
||||
|
||||
|
||||
// 点击后收起按钮菜单
|
||||
isExpanded.value = false
|
||||
}
|
||||
|
||||
// 为每个按钮计算动态样式
|
||||
const getButtonStyle = (index) => {
|
||||
// 计算过渡时间,确保显示时从上到下逐渐出现,隐藏时从下到上逐渐消失
|
||||
// 显示时间:0.9s - index * 0.2s (递减)
|
||||
// 隐藏时间:0.3s + index * 0.2s (递增)
|
||||
const showDelay = Math.max(0.1, 0.2 + index * 0.2);
|
||||
const hideDelay = 0.3 + index * 0.2;
|
||||
|
||||
// 根据是否展开返回不同的过渡样式
|
||||
if (isExpanded.value) {
|
||||
return {
|
||||
transition: `all ${showDelay}s ease-in-out`
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
transition: `all ${hideDelay}s ease-in-out`
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// 点击外部区域收起按钮的处理函数
|
||||
/**
|
||||
* 点击外部区域收起按钮的处理函数
|
||||
* @param {Event} e - 点击事件对象
|
||||
*/
|
||||
const handleClickOutside = (e) => {
|
||||
const mainButton = document.querySelector('.main-button')
|
||||
const actionButtons = document.querySelectorAll('.action-button')
|
||||
@@ -464,12 +564,20 @@ const handleClickOutside = (e) => {
|
||||
}
|
||||
}
|
||||
|
||||
// 生命周期钩子 - 挂载时添加事件监听
|
||||
// ==============================
|
||||
// 组件生命周期
|
||||
// ==============================
|
||||
|
||||
/**
|
||||
* 组件挂载时添加事件监听
|
||||
*/
|
||||
onMounted(() => {
|
||||
document.addEventListener('click', handleClickOutside)
|
||||
})
|
||||
|
||||
// 生命周期钩子 - 卸载前清理事件监听
|
||||
/**
|
||||
* 组件卸载前清理事件监听
|
||||
*/
|
||||
onBeforeUnmount(() => {
|
||||
document.removeEventListener('click', handleClickOutside)
|
||||
})
|
||||
|
||||
@@ -5,6 +5,18 @@ import api from './apiService'
|
||||
* 文章服务类
|
||||
*/
|
||||
class ArticleService {
|
||||
/**
|
||||
* 分页查询文章列表
|
||||
* @param {import('../types').PaginationParams} params - 分页查询参数
|
||||
* @param status 文章状态(0:未发表 1:已发表 2:已删除)
|
||||
* @param page 页码,从0开始(可选,默认为0)
|
||||
* @param size 每页大小(可选,默认为10,最大为100)
|
||||
* @returns {Promise<import('../types').ApiResponse<import('../types').Article[]>>}
|
||||
*/
|
||||
getArticles(params = {}) {
|
||||
return api.get(`/articles/status/page/${params.status}/${params.page}/${params.size}`, { params })
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取已发布文章列表
|
||||
* @param {import('../types').PaginationParams} params - 查询参数
|
||||
|
||||
@@ -19,9 +19,9 @@
|
||||
/* 首页 hero 区域高度和间距 */
|
||||
--hero-height: 768px;
|
||||
/* hero 默认高度 */
|
||||
--hero-height-small: 150px;
|
||||
--hero-height-small: 100px;
|
||||
/* hero 收缩后高度 */
|
||||
--hero-margin-top: 5%;
|
||||
/* --hero-margin-top: 2%; */
|
||||
/* hero 顶部外边距 */
|
||||
|
||||
/* 标题样式 */
|
||||
@@ -352,10 +352,14 @@ p {
|
||||
}
|
||||
/* 分页区样式 */
|
||||
.Pagination {
|
||||
align-self: center;
|
||||
background-color: var(--pagination-bg);
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
.Pagination .el-pagination {
|
||||
/* 水平垂直居中 */
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
/* 左侧状态栏样式 */
|
||||
.leftmodluecontainer {
|
||||
width: var(--leftmodlue-width);
|
||||
@@ -364,7 +368,6 @@ p {
|
||||
/* 首页 hero 区域样式 */
|
||||
.hero {
|
||||
height: var(--hero-height);
|
||||
margin-top: var(--hero-margin-top);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
@@ -393,10 +396,6 @@ p {
|
||||
}
|
||||
|
||||
/* hero 主标题样式 */
|
||||
.hero h1 {
|
||||
font-size: var(--title-font-size);
|
||||
margin-bottom: var(--title-margin-bottom);
|
||||
}
|
||||
|
||||
/* hero 副标题样式 */
|
||||
.hero p {
|
||||
|
||||
@@ -86,6 +86,7 @@ export interface CategoryDto {
|
||||
description?: string
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 分类属性接口
|
||||
*/
|
||||
@@ -163,6 +164,5 @@ export interface ApiResponse<T = any> {
|
||||
export interface PaginationParams {
|
||||
page?: number
|
||||
size?: number
|
||||
keyword?: string
|
||||
[key: string]: any
|
||||
status?: number
|
||||
}
|
||||
@@ -9,7 +9,7 @@
|
||||
<!-- 错误状态 -->
|
||||
<div v-else-if="error" class="error-state-container">
|
||||
<el-alert :title="error" type="error" show-icon />
|
||||
<el-button type="primary" @click="fetchArticleDetail">重新加载</el-button>
|
||||
<el-button type="primary" @click="initializeArticleDetail">重新加载</el-button>
|
||||
</div>
|
||||
|
||||
<!-- 文章详情 -->
|
||||
@@ -40,14 +40,11 @@
|
||||
<!-- 文章底部信息 -->
|
||||
<div class="article-footer-section">
|
||||
<div class="article-tag-list">
|
||||
<!-- <span v-for="tag in article.tags || []" :key="tag" class="el-tag el-tag--primary">
|
||||
{{ tag }}
|
||||
</span> -->
|
||||
</div>
|
||||
|
||||
<!-- 文章操作按钮 -->
|
||||
<div class="article-actions-group">
|
||||
<el-button type="primary" @click="goBack" plain>
|
||||
<el-button type="primary" @click="navigateBack" plain>
|
||||
返回
|
||||
</el-button>
|
||||
</div>
|
||||
@@ -57,11 +54,11 @@
|
||||
<div class="related-articles-section" v-if="relatedArticles.length > 0">
|
||||
<h3>相关文章</h3>
|
||||
<div class="related-articles-list">
|
||||
<div v-for="item in relatedArticles" :key="item.articleid" class="related-article-card"
|
||||
<!-- <div v-for="item in relatedArticles" :key="item.articleid" class="related-article-card"
|
||||
@click="handleRelatedArticleClick(item.articleid)">
|
||||
<i class="el-icon-document"></i>
|
||||
<span>{{ item.title }}</span>
|
||||
</div>
|
||||
</div> -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -80,92 +77,185 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
// 导入必要的依赖
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
// =========================================================================
|
||||
// 组件导入和初始化
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* 导入Vue核心功能
|
||||
*/
|
||||
import { ref, onMounted } from 'vue'
|
||||
|
||||
/**
|
||||
* 导入路由相关功能
|
||||
*/
|
||||
import { useRouter } from 'vue-router'
|
||||
|
||||
/**
|
||||
* 导入状态管理和UI组件
|
||||
*/
|
||||
import { useGlobalStore } from '@/store/globalStore'
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
/**
|
||||
* 导入类型和工具函数
|
||||
*/
|
||||
import type { Article } from '@/types'
|
||||
import { formatRelativeTime } from '@/utils/dateUtils'
|
||||
|
||||
/**
|
||||
* 导入子组件
|
||||
*/
|
||||
import messageboard from './messageboard.vue'
|
||||
import markdownViewer from './markdown.vue'
|
||||
// 路由相关
|
||||
|
||||
// =========================================================================
|
||||
// 路由和状态初始化
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* 初始化路由
|
||||
*/
|
||||
const router = useRouter()
|
||||
|
||||
// 响应式状态管理
|
||||
/**
|
||||
* 初始化全局状态管理
|
||||
*/
|
||||
const globalStore = useGlobalStore()
|
||||
const article = ref<Article | null>(null) // 使用 null 作为初始值,避免类型不匹配问题
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
const relatedArticles = ref<Article[]>([])
|
||||
|
||||
/**
|
||||
* 响应式状态定义
|
||||
*/
|
||||
const article = ref<Article | null>(null) // 文章详情数据,初始为null避免类型不匹配
|
||||
const loading = ref(false) // 加载状态
|
||||
const error = ref('') // 错误信息
|
||||
const relatedArticles = ref<Article[]>([]) // 相关文章列表
|
||||
|
||||
// =========================================================================
|
||||
// 文章数据处理模块
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* 获取文章ID
|
||||
* @returns {number | null} 文章ID或null
|
||||
*/
|
||||
const getArticleId = (): number | null => {
|
||||
return globalStore.getValue('articleInfo')?.articleid || null
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文章详情数据
|
||||
* @returns {Promise<Article | null>} 文章数据或null
|
||||
*/
|
||||
const fetchArticleDetail = async () => {
|
||||
const fetchArticleData = async (): Promise<Article | null> => {
|
||||
try {
|
||||
// 从全局状态获取文章信息
|
||||
const response = await globalStore.getValue('articleInfo')
|
||||
return response || null
|
||||
} catch (err) {
|
||||
console.error('获取文章数据失败:', err)
|
||||
throw new Error('获取文章数据失败')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 增加文章浏览量
|
||||
* @param {Article} articleData 文章数据
|
||||
*/
|
||||
const incrementViewCount = (articleData: Article): void => {
|
||||
if (articleData.viewCount) {
|
||||
articleData.viewCount++
|
||||
} else {
|
||||
articleData.viewCount = 1
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理文章不存在的情况
|
||||
*/
|
||||
const handleArticleNotFound = (): void => {
|
||||
error.value = '文章不存在或已被删除'
|
||||
ElMessage.error(error.value)
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理获取文章数据过程中的错误
|
||||
* @param {unknown} err 错误对象
|
||||
*/
|
||||
const handleArticleFetchError = (err: unknown): void => {
|
||||
error.value = err instanceof Error ? err.message : '获取文章详情失败,请稍后重试'
|
||||
console.error('获取文章详情失败:', err)
|
||||
ElMessage.error(error.value)
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化文章详情数据
|
||||
*/
|
||||
const initializeArticleDetail = async (): Promise<void> => {
|
||||
try {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
|
||||
// 获取路由参数
|
||||
const articleId = globalStore.getValue('articleInfo')?.articleid || null
|
||||
// 获取文章ID
|
||||
const articleId = getArticleId()
|
||||
if (!articleId) {
|
||||
throw new Error('文章不存在')
|
||||
handleArticleNotFound()
|
||||
return
|
||||
}
|
||||
// 获取文章详情
|
||||
const response = await globalStore.getValue('articleInfo')
|
||||
// const markdowndata = await
|
||||
if (response) {
|
||||
article.value = response
|
||||
// 获取并设置分类名称
|
||||
// const categoryResponse = await categoryAttributeService.getAttributeById(Number(article.value.attributeid))
|
||||
// article.value.categoryName = categoryResponse.data.attributename || '未分类'
|
||||
// 获取并设置评论量
|
||||
// const commentResponse = await messageService.getMessagesByArticleId(articleId)
|
||||
// article.value.commentCount = commentResponse.data.length || 0
|
||||
// 更新浏览量
|
||||
// 更新前端显示的浏览量
|
||||
if (article.value.viewCount) {
|
||||
article.value.viewCount++
|
||||
} else {
|
||||
article.value.viewCount = 1
|
||||
}
|
||||
|
||||
// 获取文章数据
|
||||
const articleData = await fetchArticleData()
|
||||
if (articleData) {
|
||||
article.value = articleData
|
||||
// 增加浏览量
|
||||
incrementViewCount(articleData)
|
||||
} else {
|
||||
throw new Error('文章不存在或已被删除')
|
||||
handleArticleNotFound()
|
||||
}
|
||||
} catch (err) {
|
||||
error.value = err instanceof Error ? err.message : '获取文章详情失败,请稍后重试'
|
||||
console.error('获取文章详情失败:', err)
|
||||
ElMessage.error(error.value)
|
||||
handleArticleFetchError(err)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 导航和用户交互模块
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* 返回上一页
|
||||
*/
|
||||
const goBack = () => {
|
||||
const navigateBack = (): void => {
|
||||
router.back()
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理相关文章点击事件
|
||||
* 导航到相关文章
|
||||
* @param {number} id - 相关文章ID
|
||||
*/
|
||||
const handleRelatedArticleClick = (id: number) => {
|
||||
const navigateToRelatedArticle = (id: number): void => {
|
||||
router.push({
|
||||
path: '/article/:url',
|
||||
query: { url: id }
|
||||
})
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 组件生命周期和初始化
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* 组件挂载时获取文章详情
|
||||
* 组件挂载时的初始化操作
|
||||
*/
|
||||
const setupComponent = (): void => {
|
||||
initializeArticleDetail()
|
||||
}
|
||||
/**
|
||||
* 组件挂载生命周期钩子
|
||||
*/
|
||||
onMounted(() => {
|
||||
fetchArticleDetail()
|
||||
setupComponent()
|
||||
})
|
||||
</script>
|
||||
|
||||
|
||||
@@ -32,21 +32,27 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="editor-container">
|
||||
<MdEditor v-model="Articleform.markdownscontent" class="markdown-editor" @on-save="handleSave" />
|
||||
<!-- 编辑区域 -->
|
||||
<MdEditor v-model="Articleform.markdownscontent" class="markdown-editor" @on-save="handleSave" noImgZoomIn noKatex />
|
||||
<!-- 预览 -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
import { MdEditor } from 'md-editor-v3';
|
||||
import { reactive, ref } from 'vue';
|
||||
import { MdEditor } from 'md-editor-v3';
|
||||
import 'md-editor-v3/lib/style.css';
|
||||
import { categoryService, categoryAttributeService, articleService } from '@/services';
|
||||
import type { Article } from '@/types/index.ts';
|
||||
import { ElMessage } from 'element-plus';
|
||||
import { useGlobalStore } from '@/store/globalStore'
|
||||
const globalStore = useGlobalStore()
|
||||
// 测试
|
||||
// const id = 'preview-only';
|
||||
// const scrollElement = document.documentElement;
|
||||
|
||||
// 路由
|
||||
import router from '@/router/Router';
|
||||
const Articleform = ref<Article>({
|
||||
@@ -58,7 +64,6 @@ const Articleform = ref<Article>({
|
||||
createdAt: '',
|
||||
updatedAt: '',
|
||||
markdownscontent: '',
|
||||
status: 0 // 默认状态为草稿
|
||||
})
|
||||
|
||||
// 用于级联选择器的值绑定
|
||||
|
||||
@@ -8,13 +8,9 @@
|
||||
</div>
|
||||
|
||||
<!-- 文章列表 -->
|
||||
<transition-group name="article-item" tag="div" v-else>
|
||||
<div
|
||||
class="article-card"
|
||||
v-for="article in articleList"
|
||||
:key="article.articleId"
|
||||
@click="handleArticleClick(article)"
|
||||
>
|
||||
<transition-group name="article-item" tag="div" class="article-list-content" v-else>
|
||||
<div class="article-card" v-for="article in displayedArticles" :key="article.articleId"
|
||||
@click="handleArticleClick(article)">
|
||||
<h6 class="article-title">{{ article.title }}</h6>
|
||||
<div v-if="article.marked" class="article-special-tag">标记文章</div>
|
||||
<p class="article-content-preview">{{ formatContentPreview(article.content, 150) }}</p>
|
||||
@@ -31,6 +27,8 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 分页区域 -->
|
||||
<PaginationComponent class="pagination-container" :list="articleList" :pageSize="10" @changePage="handleCurrentDataUpdate" />
|
||||
</transition-group>
|
||||
<!-- 空状态 -->
|
||||
<div v-if="!loading && articleList.length === 0" class="empty-state-container">
|
||||
@@ -42,12 +40,15 @@
|
||||
<script setup>
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import { ref, onMounted, watch } from 'vue'
|
||||
import { formatDate, formatRelativeTime } from '@/utils/dateUtils'
|
||||
import { formatRelativeTime } from '@/utils/dateUtils'
|
||||
import { formatContentPreview } from '@/utils/stringUtils'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { articleService, messageService, categoryAttributeService } from '@/services'
|
||||
import PaginationComponent from '@/views/page.vue'
|
||||
import { useGlobalStore } from '@/store/globalStore'
|
||||
|
||||
// ========== 组件初始化 ==========
|
||||
|
||||
// 全局状态管理
|
||||
const globalStore = useGlobalStore()
|
||||
|
||||
@@ -57,108 +58,190 @@ const route = useRoute()
|
||||
|
||||
// 响应式状态
|
||||
const articleList = ref([])
|
||||
const displayedArticles = ref([])
|
||||
const loading = ref(false)
|
||||
|
||||
// ========== 分页数据处理 ==========
|
||||
|
||||
/**
|
||||
* 获取文章列表
|
||||
* 处理分页组件的数据更新
|
||||
* @param {Array} data - 分页组件传递的当前页数据
|
||||
*/
|
||||
const handleCurrentDataUpdate = (data) => {
|
||||
displayedArticles.value = data
|
||||
console.log('更新后的当前页数据:', data)
|
||||
}
|
||||
|
||||
// ========== 文章数据获取模块 ==========
|
||||
|
||||
/**
|
||||
* 根据路由路径获取对应的文章列表
|
||||
* @returns {Promise<Object>} 文章列表响应数据
|
||||
*/
|
||||
const getArticlesByRoute = async () => {
|
||||
// 检查URL参数,确定获取文章的方式
|
||||
const pathSegment = route.path.split('/')[2]
|
||||
console.log('当前路由分段:', pathSegment)
|
||||
|
||||
switch (pathSegment) {
|
||||
case 'aericletype':
|
||||
// 按属性类型获取文章
|
||||
const attributeData = globalStore.getValue('attribute')
|
||||
return await articleService.getArticlesByAttributeId(attributeData?.id)
|
||||
case 'aericletitle':
|
||||
// 按标题搜索文章
|
||||
const titleData = globalStore.getValue('articleserarch')
|
||||
return await articleService.getArticlesByTitle(titleData?.name)
|
||||
case 'aericlestatus':
|
||||
// 按状态获取文章
|
||||
const statusData = globalStore.getValue('articlestatus')
|
||||
return await articleService.getArticlesByStatus(statusData?.status)
|
||||
default:
|
||||
// 默认获取所有文章
|
||||
console.log('获取所有文章列表')
|
||||
return await articleService.getAllArticles()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 为单篇文章补充额外信息(留言数量、分类名称等)
|
||||
* @param {Object} article - 文章对象
|
||||
* @returns {Promise<Object>} 补充信息后的文章对象
|
||||
*/
|
||||
const enrichArticleWithExtraInfo = async (article) => {
|
||||
try {
|
||||
// 获取留言数量
|
||||
const messageResponse = await messageService.getMessagesByArticleId(article.articleid)
|
||||
// 获取分类名称
|
||||
const categoryResponse = await categoryAttributeService.getAttributeById(article.attributeid)
|
||||
|
||||
// 设置分类名称
|
||||
article.categoryName = categoryResponse?.data?.attributename || '未分类'
|
||||
// 设置评论数量
|
||||
article.commentCount = messageResponse?.data?.length || 0
|
||||
// 标准化标记字段名
|
||||
article.marked = article.mg
|
||||
|
||||
return article
|
||||
} catch (err) {
|
||||
console.error(`获取文章${article.articleid}额外信息失败:`, err)
|
||||
// 错误情况下设置默认值
|
||||
article.commentCount = 0
|
||||
article.categoryName = '未分类'
|
||||
return article
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量为文章列表补充额外信息
|
||||
* @param {Array} articles - 原始文章列表
|
||||
* @returns {Promise<Array>} 补充信息后的文章列表
|
||||
*/
|
||||
const enrichArticlesWithExtraInfo = async (articles) => {
|
||||
const enrichedArticles = []
|
||||
|
||||
for (const article of articles) {
|
||||
const enrichedArticle = await enrichArticleWithExtraInfo(article)
|
||||
enrichedArticles.push(enrichedArticle)
|
||||
}
|
||||
|
||||
return enrichedArticles
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化显示文章列表
|
||||
* @param {Array} articles - 完整文章列表
|
||||
*/
|
||||
const initializeDisplayedArticles = (articles) => {
|
||||
// 初始显示前3条数据
|
||||
displayedArticles.value = articles.slice(0, 3)
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文章列表主函数
|
||||
*/
|
||||
const fetchArticles = async () => {
|
||||
let response = {}
|
||||
|
||||
try {
|
||||
loading.value = true
|
||||
let response = {}
|
||||
|
||||
// 检查URL参数,确定获取文章的方式
|
||||
const pathSegment = route.path.split('/')[2];
|
||||
console.log(pathSegment)
|
||||
// 根据不同路径获取不同文章
|
||||
switch (pathSegment) {
|
||||
case 'aericletype':
|
||||
// 按属性类型获取文章
|
||||
const attributeData = globalStore.getValue('attribute')
|
||||
response = await articleService.getArticlesByAttributeId(attributeData.id)
|
||||
break
|
||||
case 'aericletitle':
|
||||
// 按标题搜索文章
|
||||
const titleData = globalStore.getValue('articleserarch')
|
||||
response = await articleService.getArticlesByTitle(titleData.name)
|
||||
break
|
||||
case 'aericlestatus':
|
||||
// 按状态获取文章
|
||||
const statusData = globalStore.getValue('articlestatus')
|
||||
response = await articleService.getArticlesByStatus(statusData.status)
|
||||
break
|
||||
default:
|
||||
// 默认情况下,根据用户权限决定获取方式
|
||||
if (globalStore.Login) {
|
||||
// 获取所有文章(包含已删除)
|
||||
console.log('管理员获取所有文章列表(包含已删除)')
|
||||
response = await articleService.getAllArticlesWithDeleted()
|
||||
} else {
|
||||
// 获取所有文章
|
||||
console.log('获取所有文章列表')
|
||||
response = await articleService.getAllArticles()
|
||||
}
|
||||
// 1. 根据路由获取文章列表
|
||||
response = await getArticlesByRoute()
|
||||
|
||||
// 2. 确保数据存在
|
||||
if (!response.data || !Array.isArray(response.data)) {
|
||||
articleList.value = []
|
||||
displayedArticles.value = []
|
||||
return
|
||||
}
|
||||
|
||||
// 为每个文章获取留言数量和分类名称
|
||||
for (const article of response.data) {
|
||||
try {
|
||||
// 获取留言数量
|
||||
const messageResponse = await messageService.getMessagesByArticleId(article.articleid)
|
||||
// console.log(`文章ID: ${article.articleid}, 分类ID: ${article.attributeid}`)
|
||||
// 3. 为文章列表补充额外信息
|
||||
const enrichedArticles = await enrichArticlesWithExtraInfo(response.data)
|
||||
|
||||
// 获取分类名称
|
||||
const categoryResponse = await categoryAttributeService.getAttributeById(article.attributeid)
|
||||
// 4. 更新文章列表
|
||||
articleList.value = enrichedArticles
|
||||
|
||||
if (categoryResponse && categoryResponse.data) {
|
||||
article.categoryName = categoryResponse.data.attributename
|
||||
} else {
|
||||
article.categoryName = '未分类'
|
||||
}
|
||||
// 5. 初始化显示的文章
|
||||
initializeDisplayedArticles(enrichedArticles)
|
||||
|
||||
// 设置评论数量
|
||||
article.commentCount = messageResponse.data.length > 0 ? messageResponse.data.length : 0
|
||||
|
||||
// 标准化ID字段名
|
||||
article.articleId = article.articleid
|
||||
|
||||
// 标准化标记字段名
|
||||
article.marked = article.mg
|
||||
} catch (err) {
|
||||
console.error(`获取文章${article.articleid}留言数量失败:`, err)
|
||||
article.commentCount = 0
|
||||
}
|
||||
}
|
||||
|
||||
// 更新文章列表
|
||||
// console.log(response.data)
|
||||
articleList.value = response.data || []
|
||||
} catch (error) {
|
||||
console.error('获取文章列表失败:', error)
|
||||
ElMessage.error('获取文章列表失败,请稍后重试')
|
||||
} finally {
|
||||
console.log('最终文章列表数据:', articleList.value)
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 文章交互模块 ==========
|
||||
|
||||
/**
|
||||
* 处理文章点击事件
|
||||
* @param {Object} article - 文章对象
|
||||
*/
|
||||
const handleArticleClick = (article) => {
|
||||
// 增加文章浏览量
|
||||
articleService.incrementArticleViews(article.articleId)
|
||||
// 清除之前的文章信息
|
||||
globalStore.removeValue('articleInfo')
|
||||
// 存储文章信息到全局状态
|
||||
globalStore.setValue('articleInfo', article)
|
||||
try {
|
||||
// 增加文章浏览量(异步操作,不阻塞后续流程)
|
||||
articleService.incrementArticleViews(article.articleId).catch(err => {
|
||||
console.error('增加文章浏览量失败:', err)
|
||||
})
|
||||
|
||||
// 跳转到文章详情页
|
||||
router.push({
|
||||
path: '/article',
|
||||
})
|
||||
// 清除之前的文章信息
|
||||
globalStore.removeValue('articleInfo')
|
||||
|
||||
// 存储文章信息到全局状态
|
||||
globalStore.setValue('articleInfo', article)
|
||||
|
||||
// 跳转到文章详情页
|
||||
router.push({
|
||||
path: '/article',
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('处理文章点击事件失败:', error)
|
||||
ElMessage.error('操作失败,请稍后重试')
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 生命周期和监听器 ==========
|
||||
|
||||
/**
|
||||
* 处理路由变化的回调函数
|
||||
*/
|
||||
const handleRouteChange = () => {
|
||||
fetchArticles()
|
||||
console.log('路由变化,重新获取文章列表')
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理文章列表变化的回调函数
|
||||
* @param {Array} newList - 新的文章列表
|
||||
*/
|
||||
const handleArticleListChange = (newList) => {
|
||||
if (newList && newList.length > 0) {
|
||||
displayedArticles.value = newList.slice(0, 3)
|
||||
}
|
||||
}
|
||||
//刷新时挂载获取数据
|
||||
|
||||
// 组件挂载时获取数据
|
||||
onMounted(() => {
|
||||
@@ -170,10 +253,14 @@ watch(
|
||||
// 监听路由路径和查询参数变化
|
||||
() => [route.path, route.query],
|
||||
// 路由变化时触发获取文章列表
|
||||
() => {
|
||||
fetchArticles()
|
||||
console.log('路由变化,重新获取文章列表')
|
||||
},
|
||||
handleRouteChange,
|
||||
{ deep: true }
|
||||
)
|
||||
|
||||
// 监听原始文章列表变化,确保初始数据正确显示
|
||||
watch(
|
||||
() => articleList.value,
|
||||
handleArticleListChange,
|
||||
{ deep: true }
|
||||
)
|
||||
</script>
|
||||
@@ -182,7 +269,6 @@ watch(
|
||||
/* 文章列表容器样式 */
|
||||
.article-list-container {
|
||||
max-width: 100%;
|
||||
padding: 0 15px;
|
||||
}
|
||||
|
||||
/* 加载状态容器 */
|
||||
@@ -209,6 +295,7 @@ watch(
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
|
||||
border: 1px solid rgba(0, 0, 0, 0.05);
|
||||
}
|
||||
|
||||
/* 文章卡片悬停渐变效果 */
|
||||
.article-card::before {
|
||||
content: '';
|
||||
@@ -218,9 +305,9 @@ watch(
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: linear-gradient(135deg,
|
||||
rgba(255, 255, 255, 0.6) 0%,
|
||||
rgba(255, 255, 255, 0.2) 50%,
|
||||
rgba(255, 255, 255, 0.05) 100%);
|
||||
rgba(255, 255, 255, 0.6) 0%,
|
||||
rgba(255, 255, 255, 0.2) 50%,
|
||||
rgba(255, 255, 255, 0.05) 100%);
|
||||
pointer-events: none;
|
||||
opacity: 0;
|
||||
transition: opacity 0.4s ease;
|
||||
@@ -230,7 +317,7 @@ watch(
|
||||
.article-card:hover {
|
||||
transform: translateY(-5px);
|
||||
box-shadow: 0 12px 28px rgba(0, 0, 0, 0.15),
|
||||
0 0 30px rgba(255, 255, 255, 0.2);
|
||||
0 0 30px rgba(255, 255, 255, 0.2);
|
||||
border-color: rgba(52, 152, 219, 0.3);
|
||||
}
|
||||
|
||||
@@ -270,7 +357,18 @@ watch(
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.article-list-content {
|
||||
position: relative;
|
||||
padding: 0 0 30px 0;
|
||||
height: 100%;
|
||||
}
|
||||
.pagination-container {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
/* 文章内容预览样式 */
|
||||
.article-content-preview {
|
||||
color: #555;
|
||||
|
||||
@@ -2,34 +2,28 @@
|
||||
<div class="markdown-viewer">
|
||||
<div v-if="loading" class="loading-state">加载中...</div>
|
||||
<div v-else-if="error" class="error-state">加载失败: {{ error }}</div>
|
||||
<v-md-editor
|
||||
<!-- <v-md-editor
|
||||
v-else
|
||||
class="editor"
|
||||
v-model="content"
|
||||
mode="preview"
|
||||
:preview-theme="theme"
|
||||
:height="height"
|
||||
/>
|
||||
/> -->
|
||||
<MdPreview
|
||||
v-else
|
||||
:modelValue="content"
|
||||
class="editor"
|
||||
previewTheme="github"
|
||||
codeTheme="github" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted } from 'vue'
|
||||
// 导入v-md-editor相关组件和样式
|
||||
import VMdEditor from '@kangc/v-md-editor'
|
||||
import '@kangc/v-md-editor/lib/style/base-editor.css'
|
||||
// 导入主题(使用github主题)
|
||||
import githubTheme from '@kangc/v-md-editor/lib/theme/github.js'
|
||||
import '@kangc/v-md-editor/lib/theme/style/github.css'
|
||||
// 导入代码高亮
|
||||
import hljs from 'highlight.js'
|
||||
import 'highlight.js/styles/github.css'
|
||||
|
||||
// 配置主题
|
||||
VMdEditor.use(githubTheme, {
|
||||
Hljs: hljs
|
||||
})
|
||||
|
||||
import { MdPreview } from 'md-editor-v3'
|
||||
import 'md-editor-v3/lib/style.css'
|
||||
// 定义组件属性
|
||||
const props = defineProps({
|
||||
// 从父组件传入的markdownid内容
|
||||
@@ -37,21 +31,6 @@ const props = defineProps({
|
||||
type: String,
|
||||
default: ''
|
||||
},
|
||||
// 指定API端点
|
||||
apiEndpoint: {
|
||||
type: String,
|
||||
default: '/help'
|
||||
},
|
||||
// 编辑器高度
|
||||
height: {
|
||||
type: String,
|
||||
default: 'auto'
|
||||
},
|
||||
// 主题配置
|
||||
theme: {
|
||||
type: String,
|
||||
default: 'github'
|
||||
}
|
||||
})
|
||||
|
||||
// 响应式数据
|
||||
@@ -90,15 +69,10 @@ onMounted(() => {
|
||||
}
|
||||
|
||||
.editor {
|
||||
border: 1px solid #e0e0e0;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
|
||||
box-shadow: 0rgba(0, 0, 0, 0);
|
||||
transition: box-shadow 0.3s ease;
|
||||
background-color: rgba(255, 255, 255, 0.85);
|
||||
}
|
||||
|
||||
.editor:hover {
|
||||
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
|
||||
background-color: rgba(255, 255, 255,0);
|
||||
padding: 0 0 0 20px;
|
||||
}
|
||||
|
||||
/* 加载状态样式 */
|
||||
|
||||
@@ -131,6 +131,8 @@ import { ElMessage, ElForm } from 'element-plus'
|
||||
import { useGlobalStore } from '@/store/globalStore'
|
||||
import { formatDate } from '@/utils/dateUtils'
|
||||
|
||||
// ============================== 组件初始化 ==============================
|
||||
|
||||
// 定义组件属性
|
||||
const props = defineProps({
|
||||
comments: {
|
||||
@@ -138,65 +140,37 @@ const props = defineProps({
|
||||
default: null
|
||||
}
|
||||
})
|
||||
const globalStore = useGlobalStore()
|
||||
const messageBoardData = ref([]) // 留言板留言(articleid为空的主留言及其回复)
|
||||
const loading = ref(false)
|
||||
const submitting = ref(false)
|
||||
const replyingTo = ref({ id: null, nickname: '', content: '' })
|
||||
const formRef = ref()
|
||||
// 验证码相关状态
|
||||
const captchaHint = ref('')
|
||||
const captchaAnswer = ref('')
|
||||
const showCaptchaHint = ref(false)
|
||||
|
||||
// 全局状态管理
|
||||
const globalStore = useGlobalStore()
|
||||
|
||||
// ============================== 响应式数据 ==============================
|
||||
|
||||
// 留言板数据状态
|
||||
const messageBoardData = ref([]) // 留言板留言(articleid为空的主留言及其回复)
|
||||
const loading = ref(false) // 加载状态
|
||||
const submitting = ref(false) // 提交状态
|
||||
const replyingTo = ref({ id: null, nickname: '', content: '' }) // 正在回复的信息
|
||||
const formRef = ref() // 表单引用
|
||||
|
||||
// 验证码相关状态
|
||||
const captchaHint = ref('') // 验证码提示
|
||||
const captchaAnswer = ref('') // 验证码答案
|
||||
const showCaptchaHint = ref(false) // 是否显示验证码提示
|
||||
|
||||
// 表单数据
|
||||
const form = reactive({
|
||||
parentid: null,
|
||||
replyid: null,
|
||||
articleid: null,
|
||||
content: '',
|
||||
nickname: '',
|
||||
email: '',
|
||||
captcha: ''
|
||||
parentid: null, // 父留言ID
|
||||
replyid: null, // 被回复留言ID
|
||||
articleid: null, // 文章ID
|
||||
content: '', // 评论内容
|
||||
nickname: '', // 昵称
|
||||
email: '', // 邮箱
|
||||
captcha: '' // 验证码
|
||||
})
|
||||
|
||||
// 生成简单验证码
|
||||
const generateCaptcha = () => {
|
||||
// 随机选择数学题或字符验证码
|
||||
const isMathCaptcha = Math.random() > 0.5
|
||||
// ============================== 表单验证规则 ==============================
|
||||
|
||||
if (isMathCaptcha) {
|
||||
// 简单数学题:加法或减法
|
||||
const num1 = Math.floor(Math.random() * 10) + 1
|
||||
const num2 = Math.floor(Math.random() * 10) + 1
|
||||
const operator = Math.random() > 0.5 ? '+' : '-'
|
||||
|
||||
let answer
|
||||
if (operator === '+') {
|
||||
answer = num1 + num2
|
||||
} else {
|
||||
// 确保减法结果为正
|
||||
const larger = Math.max(num1, num2)
|
||||
const smaller = Math.min(num1, num2)
|
||||
captchaHint.value = `${larger} - ${smaller} = ?`
|
||||
captchaAnswer.value = (larger - smaller).toString()
|
||||
return
|
||||
}
|
||||
|
||||
captchaHint.value = `${num1} ${operator} ${num2} = ?`
|
||||
captchaAnswer.value = answer.toString()
|
||||
} else {
|
||||
// 简单字符验证码
|
||||
const chars = 'ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz123456789'
|
||||
let captcha = ''
|
||||
for (let i = 0; i < 4; i++) {
|
||||
captcha += chars.charAt(Math.floor(Math.random() * chars.length))
|
||||
}
|
||||
captchaHint.value = captcha
|
||||
captchaAnswer.value = captcha.toLowerCase()
|
||||
}
|
||||
}
|
||||
|
||||
// 表单验证规则
|
||||
const rules = {
|
||||
content: [
|
||||
{ required: true, message: '请输入评论内容', trigger: 'blur' },
|
||||
@@ -237,42 +211,109 @@ const rules = {
|
||||
]
|
||||
}
|
||||
|
||||
// ============================== 验证码模块 ==============================
|
||||
|
||||
// 获取Gravatar头像URL
|
||||
/**
|
||||
* 生成验证码
|
||||
* 随机选择生成数学题验证码或字符验证码
|
||||
*/
|
||||
const generateCaptcha = () => {
|
||||
// 随机选择数学题或字符验证码
|
||||
const isMathCaptcha = Math.random() > 0.5
|
||||
|
||||
if (isMathCaptcha) {
|
||||
generateMathCaptcha()
|
||||
} else {
|
||||
generateCharCaptcha()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成数学题验证码
|
||||
* 包含简单的加法或减法运算
|
||||
*/
|
||||
const generateMathCaptcha = () => {
|
||||
// 简单数学题:加法或减法
|
||||
const num1 = Math.floor(Math.random() * 10) + 1
|
||||
const num2 = Math.floor(Math.random() * 10) + 1
|
||||
const operator = Math.random() > 0.5 ? '+' : '-'
|
||||
|
||||
if (operator === '+') {
|
||||
const answer = num1 + num2
|
||||
captchaHint.value = `${num1} ${operator} ${num2} = ?`
|
||||
captchaAnswer.value = answer.toString()
|
||||
} else {
|
||||
// 确保减法结果为正
|
||||
const larger = Math.max(num1, num2)
|
||||
const smaller = Math.min(num1, num2)
|
||||
captchaHint.value = `${larger} - ${smaller} = ?`
|
||||
captchaAnswer.value = (larger - smaller).toString()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成字符验证码
|
||||
* 随机生成4位大小写字母和数字的组合
|
||||
*/
|
||||
const generateCharCaptcha = () => {
|
||||
const chars = 'ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz123456789'
|
||||
let captcha = ''
|
||||
for (let i = 0; i < 4; i++) {
|
||||
captcha += chars.charAt(Math.floor(Math.random() * chars.length))
|
||||
}
|
||||
captchaHint.value = captcha
|
||||
captchaAnswer.value = captcha.toLowerCase()
|
||||
}
|
||||
|
||||
// ============================== UI辅助模块 ==============================
|
||||
|
||||
/**
|
||||
* 获取Gravatar头像URL
|
||||
* @param {string} email - 用户邮箱
|
||||
* @returns {string|null} - 头像URL或null
|
||||
*/
|
||||
const getAvatarUrl = (email) => {
|
||||
if (!email) return null;
|
||||
|
||||
// 简单验证邮箱格式
|
||||
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
|
||||
if (!emailRegex.test(email)) return null;
|
||||
|
||||
// 使用邮箱的MD5哈希(这里简化处理,实际项目中应该使用md5库)
|
||||
// 注意:在实际项目中应该使用正确的MD5哈希函数
|
||||
return `https://www.gravatar.com/avatar/${email}?d=404&s=40`;
|
||||
}
|
||||
|
||||
// 获取名字的首字母
|
||||
/**
|
||||
* 获取名字的首字母
|
||||
* 用于生成字母头像
|
||||
* @param {string} name - 用户昵称
|
||||
* @returns {string} - 首字母或问号
|
||||
*/
|
||||
const getInitialLetter = (name) => {
|
||||
if (!name || typeof name !== 'string') return '?';
|
||||
|
||||
// 移除可能的@回复前缀
|
||||
const cleanName = name.replace(/^.+@\s*/, '');
|
||||
|
||||
// 获取第一个字符
|
||||
const firstChar = cleanName.charAt(0).toUpperCase();
|
||||
|
||||
return firstChar;
|
||||
// 获取第一个字符并转为大写
|
||||
return cleanName.charAt(0).toUpperCase();
|
||||
}
|
||||
|
||||
// 获取首字母头像的样式
|
||||
/**
|
||||
* 获取首字母头像的样式
|
||||
* 根据名字生成一致的颜色
|
||||
* @param {string} name - 用户昵称
|
||||
* @returns {Object} - 包含背景色和文字颜色的样式对象
|
||||
*/
|
||||
const getLetterAvatarStyle = (name) => {
|
||||
// 颜色映射表,根据名字生成一致的颜色
|
||||
// 预定义的颜色数组
|
||||
const colors = [
|
||||
'#4A90E2', '#50E3C2', '#F5A623', '#D0021B', '#9013FE',
|
||||
'#B8E986', '#BD10E0', '#50E3C2', '#417505', '#7ED321',
|
||||
'#BD10E0', '#F8E71C', '#8B572A', '#9B9B9B', '#4A4A4A'
|
||||
];
|
||||
|
||||
// 根据名字生成一个一致的颜色索引
|
||||
// 根据名字生成一致的颜色索引
|
||||
let hash = 0;
|
||||
if (name) {
|
||||
for (let i = 0; i < name.length; i++) {
|
||||
@@ -287,195 +328,258 @@ const getLetterAvatarStyle = (name) => {
|
||||
};
|
||||
}
|
||||
|
||||
// 从后端获取留言列表
|
||||
// ============================== 数据处理模块 ==============================
|
||||
|
||||
/**
|
||||
* 处理留言数据,构建留言与回复的层级结构
|
||||
* @param {Array} messages - 原始留言数据
|
||||
* @returns {Array} - 处理后的留言数据(包含回复数组)
|
||||
*/
|
||||
const processMessageData = (messages) => {
|
||||
// 为主留言添加replies数组
|
||||
const allMessagesWithReplies = messages.map(msg => ({
|
||||
...msg,
|
||||
replies: []
|
||||
}))
|
||||
|
||||
// 分离主留言和回复
|
||||
const mainMessages = []
|
||||
const replies = []
|
||||
|
||||
allMessagesWithReplies.forEach(msg => {
|
||||
if (msg.parentid && msg.parentid > 0) {
|
||||
replies.push(msg)
|
||||
} else {
|
||||
mainMessages.push(msg)
|
||||
}
|
||||
})
|
||||
|
||||
// 将回复添加到对应的主留言中并处理@回复显示
|
||||
processRepliesForMainMessages(mainMessages, replies)
|
||||
|
||||
return mainMessages
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理回复数据,将其添加到对应的主留言中
|
||||
* @param {Array} mainMessages - 主留言数组
|
||||
* @param {Array} replies - 回复数组
|
||||
*/
|
||||
const processRepliesForMainMessages = (mainMessages, replies) => {
|
||||
replies.forEach(reply => {
|
||||
// 找到父留言
|
||||
const parentMsg = mainMessages.find(msg => msg.messageid === reply.parentid)
|
||||
if (parentMsg) {
|
||||
// 处理@回复的显示名称
|
||||
processReplyDisplayName(reply, replies)
|
||||
parentMsg.replies.push(reply)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理回复的显示名称
|
||||
* 如果是回复其他回复,添加@标记
|
||||
* @param {Object} reply - 回复对象
|
||||
* @param {Array} allReplies - 所有回复数组
|
||||
*/
|
||||
const processReplyDisplayName = (reply, allReplies) => {
|
||||
if (reply.replyid) {
|
||||
const repliedMsg = allReplies.find(msg => msg.messageid === reply.replyid)
|
||||
if (repliedMsg) {
|
||||
reply.displayName = `${reply.nickname}@ ${repliedMsg.nickname}`
|
||||
} else {
|
||||
reply.displayName = reply.nickname
|
||||
}
|
||||
} else {
|
||||
reply.displayName = reply.nickname
|
||||
}
|
||||
}
|
||||
|
||||
// ============================== API调用模块 ==============================
|
||||
|
||||
/**
|
||||
* 从后端获取留言列表
|
||||
* 根据articleid决定获取文章留言还是全局留言
|
||||
*/
|
||||
const fetchMessages = async () => {
|
||||
try {
|
||||
loading.value = true
|
||||
let res = null
|
||||
|
||||
// 优先使用props传递的articleid,其次使用globalStore中的数据
|
||||
let articleid = props.comments || null
|
||||
|
||||
if (!articleid) {
|
||||
// 安全获取文章ID,如果globalStore中没有articleInfo则返回null
|
||||
const articleData = globalStore.getValue('articleInfo')
|
||||
articleid = (articleData && typeof articleData === 'object' && 'articleid' in articleData) ? articleData.articleid : null
|
||||
}
|
||||
|
||||
// 获取文章ID(优先使用props,其次使用全局状态)
|
||||
const articleid = getArticleId()
|
||||
form.articleid = articleid
|
||||
|
||||
// 根据是否有文章ID选择不同的API调用
|
||||
if (articleid) {
|
||||
res = await messageService.getMessagesByArticleId(articleid)
|
||||
} else {
|
||||
res = await messageService.getAllMessages()
|
||||
// 过滤掉articleid不为空的留言,只保留articleid为空或不存在的留言
|
||||
if (res && res.data) {
|
||||
res.data = res.data.filter(msg => !msg.articleid || msg.articleid === '')
|
||||
}
|
||||
}
|
||||
res = await (articleid
|
||||
? messageService.getMessagesByArticleId(articleid)
|
||||
: fetchAllMessages()
|
||||
)
|
||||
|
||||
// 验证响应结果
|
||||
if (!res || !res.data) {
|
||||
console.warn('未获取到留言数据')
|
||||
messageBoardData.value = []
|
||||
handleEmptyResponse()
|
||||
return
|
||||
}
|
||||
|
||||
const allMessages = res.data
|
||||
|
||||
// 处理所有留言,为主留言添加replies数组
|
||||
const allMessagesWithReplies = allMessages.map(msg => ({
|
||||
...msg,
|
||||
replies: []
|
||||
}))
|
||||
|
||||
// 分离主留言和回复
|
||||
const mainMessages = []
|
||||
const replies = []
|
||||
|
||||
allMessagesWithReplies.forEach(msg => {
|
||||
if (msg.parentid && msg.parentid > 0) {
|
||||
replies.push(msg)
|
||||
} else {
|
||||
mainMessages.push(msg)
|
||||
}
|
||||
})
|
||||
|
||||
// 将回复添加到对应的主留言中
|
||||
replies.forEach(reply => {
|
||||
// 找到父留言
|
||||
const parentMsg = mainMessages.find(msg => msg.messageid === reply.parentid)
|
||||
if (parentMsg) {
|
||||
// 处理@回复的显示名称
|
||||
if (reply.replyid) {
|
||||
const repliedMsg = replies.find(msg => msg.messageid === reply.replyid)
|
||||
if (repliedMsg) {
|
||||
reply.displayName = `${reply.nickname}@ ${repliedMsg.nickname}`
|
||||
} else {
|
||||
reply.displayName = reply.nickname
|
||||
}
|
||||
} else {
|
||||
reply.displayName = reply.nickname
|
||||
}
|
||||
parentMsg.replies.push(reply)
|
||||
}
|
||||
})
|
||||
|
||||
// 更新留言板数据
|
||||
messageBoardData.value = mainMessages
|
||||
// 处理留言数据
|
||||
messageBoardData.value = processMessageData(res.data)
|
||||
} catch (error) {
|
||||
console.error('获取留言列表失败:', error)
|
||||
ElMessage.error('获取留言失败,请稍后重试')
|
||||
messageBoardData.value = [] // 出错时清空数据,避免显示错误内容
|
||||
handleFetchError(error)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 处理回复
|
||||
const handleReply = (msg, reply) => {
|
||||
// 检查是否是回复模式
|
||||
if (msg !== null) {
|
||||
// 回复模式
|
||||
form.replyid = reply.messageid
|
||||
form.parentid = msg.messageid
|
||||
} else {
|
||||
// 普通回复模式
|
||||
form.replyid = null
|
||||
form.parentid = reply.messageid
|
||||
/**
|
||||
* 获取文章ID
|
||||
* 优先级:props.comments > globalStore中的articleInfo
|
||||
* @returns {number|null} - 文章ID或null
|
||||
*/
|
||||
const getArticleId = () => {
|
||||
let articleid = props.comments || null
|
||||
|
||||
if (!articleid) {
|
||||
// 安全获取文章ID,如果globalStore中没有articleInfo则返回null
|
||||
const articleData = globalStore.getValue('articleInfo')
|
||||
articleid = (articleData && typeof articleData === 'object' && 'articleid' in articleData)
|
||||
? articleData.articleid
|
||||
: null
|
||||
}
|
||||
|
||||
return articleid
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有留言并过滤
|
||||
* 只保留articleid为空或不存在的全局留言
|
||||
* @returns {Promise} - API响应
|
||||
*/
|
||||
const fetchAllMessages = async () => {
|
||||
const res = await messageService.getAllMessages()
|
||||
// 过滤掉articleid不为空的留言,只保留articleid为空或不存在的留言
|
||||
if (res && res.data) {
|
||||
res.data = res.data.filter(msg => !msg.articleid || msg.articleid === '')
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理空响应
|
||||
*/
|
||||
const handleEmptyResponse = () => {
|
||||
console.warn('未获取到留言数据')
|
||||
messageBoardData.value = []
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理获取留言错误
|
||||
* @param {Error} error - 错误对象
|
||||
*/
|
||||
const handleFetchError = (error) => {
|
||||
console.error('获取留言列表失败:', error)
|
||||
ElMessage.error('获取留言失败,请稍后重试')
|
||||
messageBoardData.value = [] // 出错时清空数据,避免显示错误内容
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交留言
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
const submitMessage = async () => {
|
||||
const res = await messageService.saveMessage({
|
||||
content: form.content,
|
||||
nickname: form.nickname,
|
||||
email: form.email,
|
||||
parentid: form.parentid,
|
||||
replyid: form.replyid,
|
||||
articleid: form.articleid
|
||||
})
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
/**
|
||||
* 点赞留言
|
||||
* @param {number} messageId - 留言ID
|
||||
* @returns {Promise} - API响应
|
||||
*/
|
||||
const likeMessage = async (messageId) => {
|
||||
return await messageService.likeMessage(messageId)
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除留言
|
||||
* @param {number} messageId - 留言ID
|
||||
* @returns {Promise} - API响应
|
||||
*/
|
||||
const deleteMessage = async (messageId) => {
|
||||
return await messageService.deleteMessage(messageId)
|
||||
}
|
||||
|
||||
// ============================== 交互操作模块 ==============================
|
||||
|
||||
/**
|
||||
* 处理回复操作
|
||||
* @param {Object|null} msg - 主留言对象,null表示直接回复主留言
|
||||
* @param {Object} reply - 被回复的留言对象
|
||||
*/
|
||||
const handleReply = (msg, reply) => {
|
||||
// 设置回复相关表单数据
|
||||
setupReplyFormData(msg, reply)
|
||||
|
||||
// 记录正在回复的信息
|
||||
replyingTo.value = {
|
||||
id: reply.messageid,
|
||||
nickname: reply.nickname || '匿名用户',
|
||||
content: reply.content
|
||||
}
|
||||
|
||||
// 滚动到输入框
|
||||
scrollToInput()
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置回复表单数据
|
||||
* @param {Object|null} msg - 主留言对象
|
||||
* @param {Object} reply - 被回复的留言对象
|
||||
*/
|
||||
const setupReplyFormData = (msg, reply) => {
|
||||
if (msg !== null) {
|
||||
// 回复模式:回复某条回复
|
||||
form.replyid = reply.messageid
|
||||
form.parentid = msg.messageid
|
||||
} else {
|
||||
// 普通回复模式:回复主留言
|
||||
form.replyid = null
|
||||
form.parentid = reply.messageid
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 滚动到输入框区域
|
||||
*/
|
||||
const scrollToInput = () => {
|
||||
setTimeout(() => {
|
||||
document.querySelector('.message-form-section')?.scrollIntoView({ behavior: 'smooth' })
|
||||
document.querySelector('.message-form-section')?.scrollIntoView({
|
||||
behavior: 'smooth'
|
||||
})
|
||||
}, 100)
|
||||
}
|
||||
|
||||
// 取消回复
|
||||
/**
|
||||
* 取消回复
|
||||
*/
|
||||
const cancelReply = () => {
|
||||
replyingTo.value = { id: null, nickname: '', content: '' }
|
||||
form.replyid = null
|
||||
form.content = ''
|
||||
}
|
||||
|
||||
// 监听articleid变化,重新加载留言
|
||||
watch(() => props.comments, (newVal) => {
|
||||
if (newVal) {
|
||||
fetchMessages()
|
||||
}
|
||||
}, { immediate: false })
|
||||
|
||||
// 组件挂载时获取留言列表
|
||||
onMounted(() => {
|
||||
fetchMessages()
|
||||
generateCaptcha() // 页面加载时生成验证码
|
||||
})
|
||||
|
||||
|
||||
const onSubmit = async () => {
|
||||
if (!formRef.value) return;
|
||||
|
||||
// 表单验证
|
||||
await formRef.value.validate((valid) => {
|
||||
if (!valid) {
|
||||
ElMessage.warning('请检查表单填写是否正确');
|
||||
throw new Error('表单验证失败');
|
||||
}
|
||||
});
|
||||
console.log('提交留言表单:', form)
|
||||
try {
|
||||
submitting.value = true
|
||||
|
||||
if (form.parentid) {
|
||||
// 回复模式
|
||||
const res = await messageService.saveMessage({
|
||||
content: form.content,
|
||||
nickname: form.nickname,
|
||||
email: form.email,
|
||||
parentid: form.parentid,
|
||||
replyid: form.replyid,
|
||||
articleid: form.articleid
|
||||
})
|
||||
|
||||
if (res.success) {
|
||||
ElMessage.success('回复成功')
|
||||
fetchMessages() // 重新获取列表
|
||||
resetForm()
|
||||
cancelReply()
|
||||
} else {
|
||||
ElMessage.error('回复失败:' + (res.message || '未知错误'))
|
||||
}
|
||||
} else {
|
||||
// 普通留言
|
||||
const res = await messageService.saveMessage({
|
||||
content: form.content,
|
||||
nickname: form.nickname,
|
||||
email: form.email,
|
||||
articleid: form.articleid
|
||||
})
|
||||
|
||||
if (res.success) {
|
||||
ElMessage.success('留言成功')
|
||||
fetchMessages() // 重新获取列表
|
||||
resetForm()
|
||||
} else {
|
||||
ElMessage.error('留言失败:' + (res.message || '未知错误'))
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('提交失败:', error)
|
||||
ElMessage.error('网络错误,请稍后重试')
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 重置表单
|
||||
/**
|
||||
* 重置表单
|
||||
*/
|
||||
const resetForm = () => {
|
||||
form.replyid = null
|
||||
form.content = ''
|
||||
@@ -487,19 +591,79 @@ const resetForm = () => {
|
||||
replyingTo.value = { id: null, nickname: '', content: '' }
|
||||
}
|
||||
|
||||
const post_comment_reply_cancel = () => {
|
||||
form.content = ''
|
||||
form.replyid = null
|
||||
replyingTo.value = { id: null, nickname: '', content: '' }
|
||||
/**
|
||||
* 提交评论
|
||||
*/
|
||||
const onSubmit = async () => {
|
||||
if (!formRef.value) return;
|
||||
|
||||
try {
|
||||
// 表单验证
|
||||
await validateForm()
|
||||
console.log('提交留言表单:', form)
|
||||
|
||||
submitting.value = true
|
||||
|
||||
// 发送留言并处理结果
|
||||
await handleMessageSubmission()
|
||||
} catch (error) {
|
||||
console.error('提交失败:', error)
|
||||
ElMessage.error('网络错误,请稍后重试')
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 处理点赞
|
||||
/**
|
||||
* 验证表单
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
const validateForm = async () => {
|
||||
return new Promise((resolve, reject) => {
|
||||
formRef.value.validate((valid) => {
|
||||
if (!valid) {
|
||||
ElMessage.warning('请检查表单填写是否正确');
|
||||
reject(new Error('表单验证失败'));
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理留言提交
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
const handleMessageSubmission = async () => {
|
||||
const res = await submitMessage()
|
||||
|
||||
if (res.success) {
|
||||
// 提交成功
|
||||
ElMessage.success(form.parentid ? '回复成功' : '留言成功')
|
||||
await fetchMessages() // 重新获取列表
|
||||
resetForm()
|
||||
|
||||
// 如果是回复模式,取消回复状态
|
||||
if (form.parentid) {
|
||||
cancelReply()
|
||||
}
|
||||
} else {
|
||||
// 提交失败
|
||||
ElMessage.error(`${form.parentid ? '回复' : '留言'}失败:${res.message || '未知错误'}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理点赞操作
|
||||
* @param {Object} msg - 留言对象
|
||||
*/
|
||||
const handleLike = async (msg) => {
|
||||
try {
|
||||
// 显示加载状态或禁用按钮
|
||||
// 显示加载状态
|
||||
msg.isLiking = true
|
||||
|
||||
const res = await messageService.likeMessage(msg.messageid)
|
||||
const res = await likeMessage(msg.messageid)
|
||||
|
||||
if (res.success && res.data) {
|
||||
// 更新点赞数
|
||||
@@ -515,19 +679,23 @@ const handleLike = async (msg) => {
|
||||
msg.isLiking = false
|
||||
}
|
||||
}
|
||||
// 处理删除
|
||||
const handleDelete = async (msg) => {
|
||||
|
||||
/**
|
||||
* 处理删除操作
|
||||
* @param {number} messageId - 留言ID
|
||||
*/
|
||||
const handleDelete = async (messageId) => {
|
||||
// 确认删除
|
||||
if (!confirm('确定删除吗?')) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
// 显示加载状态或禁用按钮
|
||||
// msg.isDeleting = true
|
||||
if (!confirm('确定删除吗?')) {
|
||||
return
|
||||
}
|
||||
const res = await messageService.deleteMessage(msg.messageid)
|
||||
const res = await deleteMessage(messageId)
|
||||
|
||||
if (res.success) {
|
||||
// 从列表中移除
|
||||
messageBoardData.value = messageBoardData.value.filter(item => item.messageid !== msg.messageid)
|
||||
messageBoardData.value = messageBoardData.value.filter(item => item.messageid !== messageId)
|
||||
ElMessage.success('删除成功')
|
||||
} else {
|
||||
ElMessage.error('删除失败:' + (res.message || '未知错误'))
|
||||
@@ -535,10 +703,32 @@ const handleDelete = async (msg) => {
|
||||
} catch (error) {
|
||||
console.error('删除失败:', error)
|
||||
ElMessage.error('网络错误,请稍后重试')
|
||||
} finally {
|
||||
// msg.isDeleting = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 另一个取消回复的方法(冗余但保留以兼容现有代码)
|
||||
*/
|
||||
const post_comment_reply_cancel = () => {
|
||||
form.content = ''
|
||||
form.replyid = null
|
||||
replyingTo.value = { id: null, nickname: '', content: '' }
|
||||
}
|
||||
|
||||
// ============================== 生命周期和监听器 ==============================
|
||||
|
||||
// 监听articleid变化,重新加载留言
|
||||
watch(() => props.comments, (newVal) => {
|
||||
if (newVal) {
|
||||
fetchMessages()
|
||||
}
|
||||
}, { immediate: false })
|
||||
|
||||
// 组件挂载时初始化
|
||||
onMounted(() => {
|
||||
fetchMessages() // 获取留言列表
|
||||
generateCaptcha() // 生成验证码
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<div class="nonsense-container">
|
||||
<div class="nonsense-list">
|
||||
<div class="nonsense-item" v-for="item in nonsenseList" :key="item.id">
|
||||
<div class="nonsense-item" v-for="item in displayedNonsenseList" :key="item.id">
|
||||
<div class="nonsense-meta-info">
|
||||
<span class="nonsense-time">{{ formatRelativeTime(item.time) }}</span>
|
||||
<div class="article-status-badge-container" v-if="globalStore.Login">
|
||||
@@ -17,6 +17,9 @@
|
||||
:style="getCharStyle(item.id, index)">{{ char }}</span>
|
||||
</div>
|
||||
</div>
|
||||
// 分页区域
|
||||
<PaginationComponent class="pagination-container" :list="nonsenseList" :pageSize="10"
|
||||
@changePage="handleCurrentDataUpdate" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -25,6 +28,8 @@
|
||||
import { ref, onMounted, onBeforeUnmount } from 'vue'
|
||||
import { nonsenseService } from '@/services'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { ElMessageBox } from 'element-plus'
|
||||
import PaginationComponent from '@/views/page.vue'
|
||||
import { formatRelativeTime } from '@/utils/dateUtils'
|
||||
import { useGlobalStore } from '@/store/globalStore'
|
||||
const globalStore = useGlobalStore()
|
||||
@@ -37,6 +42,13 @@ const nonsenseList = ref([])
|
||||
// 存储字符引用和样式的映射
|
||||
const charRefs = ref(new Map())
|
||||
const charStyles = ref(new Map())
|
||||
// 显示的吐槽内容列表
|
||||
const displayedNonsenseList = ref([])
|
||||
// 处理分页数据更新
|
||||
const handleCurrentDataUpdate = (data) => {
|
||||
displayedNonsenseList.value = data
|
||||
console.log(data)
|
||||
}
|
||||
|
||||
// 定时器引用
|
||||
let colorChangeTimer = null
|
||||
@@ -62,7 +74,7 @@ const loadNonsenseList = async () => {
|
||||
const handleEdit = (item) => {
|
||||
// 清除更新文章状态
|
||||
|
||||
ElMessageBox.prompt('请输入您的疯言疯语:', '发表疯言疯语', {
|
||||
ElMessageBox.prompt('请输入您的疯言疯语:', '发表疯言疯语', {
|
||||
confirmButtonText: '保存',
|
||||
cancelButtonText: '取消',
|
||||
inputValue: item.content,
|
||||
@@ -266,7 +278,6 @@ onBeforeUnmount(() => {
|
||||
.nonsense-container {
|
||||
/* background-color: rgba(255, 255, 255, 0.85); */
|
||||
border-radius: 12px;
|
||||
padding: 32px 20px 24px 20px;
|
||||
/* box-shadow: 0 2px 12px rgba(0,0,0,0.06); */
|
||||
transition: box-shadow 0.3s ease;
|
||||
}
|
||||
@@ -328,6 +339,7 @@ onBeforeUnmount(() => {
|
||||
margin-bottom: 8px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.nonsense-meta-info span {
|
||||
padding: 4px 8px;
|
||||
margin-right: 8px;
|
||||
|
||||
199
src/views/page.vue
Normal file
199
src/views/page.vue
Normal file
@@ -0,0 +1,199 @@
|
||||
<template>
|
||||
<div class="pagination-container">
|
||||
<!-- 数据渲染区域 -->
|
||||
|
||||
<!-- 分页按钮区域 - 只在需要分页时显示(totalPages > 0 且 list.length <= pageSize) -->
|
||||
<div class="pagination-controls" v-if="totalPages > 1 ">
|
||||
<button
|
||||
v-for="page in totalPages"
|
||||
:key="page"
|
||||
:class="['pagination-btn', { active: currentPage === page }]"
|
||||
@click="changePage(page)"
|
||||
>
|
||||
{{ page }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch, onMounted } from 'vue'
|
||||
|
||||
// 定义组件名称
|
||||
defineOptions({
|
||||
name: 'PaginationComponent'
|
||||
})
|
||||
|
||||
// 定义props
|
||||
interface Props {
|
||||
list: any[]
|
||||
pageSize?: number
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
list: () => [],
|
||||
pageSize: 10
|
||||
})
|
||||
|
||||
// 定义响应式数据
|
||||
const currentPage = ref(1)
|
||||
const groupedData = ref<any[]>([])
|
||||
|
||||
// 定义事件
|
||||
const emit = defineEmits<{
|
||||
changePage: [data: any[]]
|
||||
}>()
|
||||
|
||||
// 计算属性 - 计算总页数
|
||||
const totalPages = computed(() => {
|
||||
// 如果列表为空,返回0
|
||||
if (!props.list || props.list.length === 0) return 0
|
||||
// 如果列表长度小于pageSize,不进行分组,返回0表示不分页
|
||||
if (props.list.length <= props.pageSize) return 0
|
||||
console.log(props.list.length, props.pageSize)
|
||||
|
||||
// 列表长度小于等于pageSize时,正常计算页数
|
||||
// 如果能整除,直接返回商
|
||||
if (props.list.length % props.pageSize === 0) {
|
||||
return props.list.length / props.pageSize
|
||||
}
|
||||
|
||||
// 不能整除时,返回商+1(用户需求:将余数添加到最后一组)
|
||||
return Math.floor(props.list.length / props.pageSize) + 1
|
||||
})
|
||||
|
||||
// 计算当前页数据
|
||||
const currentPageData = computed(() => {
|
||||
// 如果列表为空,返回空数组
|
||||
if (!props.list || props.list.length === 0) {
|
||||
return []
|
||||
}
|
||||
|
||||
// 如果列表长度小于pageSize,不分组,直接返回完整列表
|
||||
if (props.list.length <= props.pageSize) {
|
||||
return [...props.list]
|
||||
}
|
||||
|
||||
// 如果总页数为0(列表为空的情况已处理),返回空数组
|
||||
if (totalPages.value === 0) {
|
||||
return []
|
||||
}
|
||||
|
||||
// 确保当前页码不超过总页数
|
||||
if (currentPage.value > totalPages.value) {
|
||||
currentPage.value = 1
|
||||
}
|
||||
|
||||
// 正常分组逻辑
|
||||
const startIndex = (currentPage.value - 1) * props.pageSize
|
||||
let endIndex = startIndex + props.pageSize
|
||||
|
||||
// 对于最后一页,确保不会超出列表范围
|
||||
if (currentPage.value === totalPages.value) {
|
||||
endIndex = props.list.length
|
||||
}
|
||||
|
||||
return props.list.slice(startIndex, endIndex)
|
||||
})
|
||||
|
||||
// 方法 - 重新实现分组逻辑
|
||||
const groupData = () => {
|
||||
groupedData.value = []
|
||||
|
||||
// 如果列表为空或长度大于pageSize,不进行分组
|
||||
if (!props.list || props.list.length === 0 || props.list.length > props.pageSize) {
|
||||
return
|
||||
}
|
||||
|
||||
const listLength = props.list.length
|
||||
|
||||
// 正常分组逻辑,余数会自动添加到最后一组
|
||||
for (let i = 0; i < listLength; i += props.pageSize) {
|
||||
groupedData.value.push(props.list.slice(i, i + props.pageSize))
|
||||
}
|
||||
}
|
||||
|
||||
const changePage = (page: number) => {
|
||||
// 只有在需要分页的情况下才处理页码变化
|
||||
if (totalPages.value > 0 && page >= 1 && page <= totalPages.value) {
|
||||
currentPage.value = page
|
||||
// 发出事件,传递当前页数据
|
||||
emit('changePage', currentPageData.value)
|
||||
} else if (props.list && props.list.length > 0) {
|
||||
// 当不分组时,直接传递完整列表
|
||||
emit('changePage', [...props.list])
|
||||
}
|
||||
}
|
||||
|
||||
// 监听数据变化
|
||||
watch(() => props.list, () => {
|
||||
currentPage.value = 1
|
||||
groupData()
|
||||
// 数据变化时,立即发出当前数据
|
||||
emit('changePage', currentPageData.value)
|
||||
}, { deep: true })
|
||||
|
||||
// 生命周期钩子
|
||||
onMounted(() => {
|
||||
groupData()
|
||||
// 组件挂载时,立即发出初始数据
|
||||
emit('changePage', currentPageData.value)
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.pagination-container {
|
||||
width: 100%;
|
||||
padding: 20px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.data-content {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.data-item {
|
||||
padding: 10px;
|
||||
border: 1px solid #e0e0e0;
|
||||
margin-bottom: 8px;
|
||||
border-radius: 4px;
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
|
||||
.no-data {
|
||||
text-align: center;
|
||||
color: #999;
|
||||
padding: 40px 0;
|
||||
}
|
||||
|
||||
.pagination-controls {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.pagination-btn {
|
||||
padding: 8px 16px;
|
||||
border: 1px solid #d0d0d0;
|
||||
background-color: #fff;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.pagination-btn:hover {
|
||||
background-color: #f0f0f0;
|
||||
}
|
||||
|
||||
.pagination-btn.active {
|
||||
background-color: #1890ff;
|
||||
color: #fff;
|
||||
border-color: #1890ff;
|
||||
}
|
||||
|
||||
.pagination-btn.active:hover {
|
||||
background-color: #40a9ff;
|
||||
}
|
||||
</style>
|
||||
Reference in New Issue
Block a user