Compare commits

...

2 Commits

Author SHA1 Message Date
qingfeng1121
5b3fba7bfb feat: 重构留言板功能并优化UI样式
重构留言板功能,移除嵌套留言Demo页面,优化留言数据结构。新增验证码功能防止垃圾留言,改进留言列表UI样式。添加留言回复功能,支持@用户显示。优化全局状态管理,增加localStorage持久化功能。

更新技术栈依赖,包括Element Plus图标和Undraw UI组件库。调整文章详情页布局,整合留言板到文章页。修复文章浏览量统计接口路径问题,统一使用viewCount字段。

优化移动端响应式布局,改进留言表单验证逻辑。新增留言相关文章显示功能,完善用户头像生成逻辑。调整首页文章卡片样式,增加阅读量、点赞数和评论数显示。
2025-10-22 13:28:47 +08:00
qingfeng1121
b042e2a511 feat: 添加Pinia全局状态管理并重构路由逻辑
添加Pinia作为全局状态管理工具,重构路由参数传递方式
移除URL中的动态参数,改为通过Pinia store传递数据
优化导航菜单样式和交互效果,修复路由激活状态问题
新增全局状态管理示例文档,说明基础使用方法
调整页面布局和样式,提升用户体验
2025-10-20 11:59:53 +08:00
18 changed files with 1840 additions and 696 deletions

View File

@@ -1,5 +1,6 @@
{
"include": ["src/**/*"],
"compilerOptions": {
"paths": {

932
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -13,10 +13,16 @@
"test:unit": "vitest"
},
"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.2",
"element-plus": "^2.11.5",
"naive-ui": "^2.43.1",
"pinia": "^3.0.3",
"sass": "^1.93.2",
"undraw-ui": "^1.3.2",
"vue": "^3.5.18",
"vue-router": "^4.5.1"
},
@@ -25,7 +31,7 @@
"@vue/test-utils": "^2.4.6",
"jsdom": "^26.1.0",
"unplugin-auto-import": "^20.1.0",
"unplugin-vue-components": "^29.0.0",
"unplugin-vue-components": "^29.2.0",
"vite": "^7.0.6",
"vite-plugin-vue-devtools": "^8.0.0",
"vitest": "^3.2.4"

View File

@@ -10,12 +10,12 @@
</div>
<div id="cont">
<div class="cont1">
<h2>小颠片刻</h2>
<h3>小颠片刻</h3>
<p>左眼右右眼左四十五度成就美</p>
</div>
<div class="cont2">
<el-menu :default-active="activeIndex" class="el-menu-vertical-demo" @select="handleSelect">
<el-menu-item index="/:type">
<el-menu-item index="/home">
<el-icon>
</el-icon>
<span>首页</span>
@@ -124,15 +124,16 @@ onUnmounted(() => {
.cont1 {
text-align: center;
padding: 25px;
background-color: rgba(102, 161, 216, 0.9); /* 蓝色半透明背景 */
border-radius: 10px 10px 0 0;
}
.cont1 h2 {
color: #333;
.cont1 h3 {
margin-bottom: 10px;
}
.cont1 p {
color: #666;
color: white;
font-size: 14px;
}
@@ -144,9 +145,18 @@ onUnmounted(() => {
display: block;
background-color: rgba(0, 0, 0,0 ); /* 白色半透明背景 */
}
.cont2 .el-menu-vertical-demo ul li:hover{
background-color: rgba(220, 53, 69, 0.9); /* 红色半透明背景 */
color: white;
.cont2 .el-menu-vertical-demo .el-menu-item:nth-child(3){
border-radius: 0 0 10px 10px;
}
.cont2 .el-menu-vertical-demo .el-menu-item:hover{
background-color: rgba(64, 158, 255, 0.9);
}
.cont2 .el-menu-vertical-demo .el-menu-item.is-active:hover{
color: black; /* 蓝色半透明背景 */
}
.cont2 .el-menu-vertical-demo .el-menu-item.is-active{
color: var(--nav-is-active);
}
/* 分类列表样式 */

View File

@@ -9,19 +9,19 @@
<el-col :span="14" justify="center">
<div class="grid-content ep-bg-purple-dark">
<el-menu :default-active="activeIndex" class="el-menu-demo" :collapse="false" @select="handleSelect">
<el-menu-item index="/home">
<el-menu-item index="home">
首页
</el-menu-item>
<el-menu-item index="/article-list">
<el-menu-item index="article-list">
目录
</el-menu-item>
<el-menu-item index="/nonsense">
<el-menu-item index="nonsense">
疯言疯语
</el-menu-item>
<el-menu-item index="/about">
<el-menu-item index="about">
关于
</el-menu-item>
<el-menu-item index="/message">
<el-menu-item index="message">
留言板
</el-menu-item>
</el-menu>
@@ -81,6 +81,9 @@ import LeftModule from '@/components/LeftModule.vue';
// 路由相关
const router = useRouter();
const route = useRoute();
// 全局状态管理
import { useGlobalStore } from '@/store/globalStore'
const globalStore = useGlobalStore()
// 响应式状态
const classhero = ref(false);
@@ -89,9 +92,10 @@ const isScrollingleftmodlue = ref(false);
const elrowtop = ref('transparent');
const classnonsenset = 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('/')[1];
// 搜索相关状态
const isSearchBoxOpen = ref(false);
@@ -99,7 +103,7 @@ const searchKeyword = ref('');
let searchCloseTimer: number | undefined;
// 打字机效果相关
const fullHeroText = '测试打字机效果';
let fullHeroText = '测试打字机效果';
const heroText = ref('');
let heroIndex = 0;
let heroTimer: number | undefined;
@@ -125,7 +129,8 @@ const startTypewriter = () => {
* 菜单选择跳转
*/
const handleSelect = (key: string) => {
router.push({ path: key });
globalStore.clearAll()
router.push({ path: '/' + key });
};
/**
@@ -181,16 +186,19 @@ const performSearch = () => {
*/
const updatePageState = (url: string) => {
classhero.value = url !== localhome;
classnonsenset.value = url === '/nonsense';
classnonsenset.value = url === 'nonsense';
};
/**
* 设置当前激活的菜单项
*/
const setActiveIndex = (path: string) => {
activeIndex.value = path;
console.log('设置激活索引:', path);
activeIndex.value =path;
};
/**
* 处理窗口大小变化
*/
@@ -198,7 +206,7 @@ const handleResize = () => {
windowwidth.value = window.innerWidth > 768;
// 根据屏幕大小调整内容区可见性
if (route.path === localhome) {
if (rpsliturl === localhome) {
isconts.value = window.innerWidth <= 768 ? true : false;
}
};
@@ -221,7 +229,7 @@ const handleScroll = () => {
}
// 首页内容区滚动动画
if (route.path === localhome) {
if (rpsliturl === localhome) {
isconts.value = window.scrollY > 200;
isScrollingleftmodlue.value = window.scrollY > 600;
}
@@ -231,16 +239,30 @@ const handleScroll = () => {
* 监听路由变化
*/
watch(() => route.path, (newPath) => {
updatePageState(newPath);
setActiveIndex(newPath);
rpsliturl = route.path.split('/')[1];
updatePageState(rpsliturl);
setActiveIndex(rpsliturl);
const localname = route.path.split('/')[2];
let articledata;
// 优先使用attributeId参数新接口
if (localname==='aericletype') {
articledata = globalStore.getValue('attribute')
}
// 搜索标题
if (localname==='aericletitle') {
articledata = globalStore.getValue('title')
}
// hero 标题
if (articledata) {
fullHeroText = articledata.name
}
// 跳转后回到顶部
window.scrollTo({ top: 0, behavior: 'smooth' });
// 首页内容区滚动动画仅大屏下生效
if (newPath === localhome) {
if (newPath.split('/')[1] === localhome) {
isconts.value = window.innerWidth <= 768 ? true : false;
// 首页时启动打字机
// 首页时启动打字机效果
startTypewriter();
} else {
isconts.value = true;
@@ -257,7 +279,6 @@ onMounted(() => {
handleResize();
// 添加事件监听器
window.addEventListener('resize', handleResize);
window.addEventListener('scroll', handleScroll);

View File

@@ -1,11 +1,29 @@
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import Router from './router/Router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import UndrawUi from 'undraw-ui'
import 'undraw-ui/dist/style.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import './styles/MainLayout.css'
// 创建Pinia实例
const pinia = createPinia()
const app = createApp(App)
app.use(UndrawUi)
app.use(Router)
app.use(ElementPlus)
app.use(pinia) // 添加Pinia支持
// 注册所有Element Plus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component)
}
app.mount('#app')

View File

@@ -6,7 +6,6 @@ import NonsensePage from '../views/nonsense.vue'
import MessageBoardPage from '../views/messageboard.vue'
import AboutMePage from '../views/aboutme.vue'
import ArticleContentPage from '../views/articlecontents.vue'
import CommentDemoPage from '../views/commentDemo.vue'
/**
* 路由配置数组
@@ -17,14 +16,6 @@ const routes = [
path: '/',
redirect: '/home' // 默认跳转到首页,显示所有文章
},
{
path: '/comment-demo',
name: 'commentDemo',
component: CommentDemoPage,
meta: {
title: '嵌套留言Demo'
}
},
{
path: '/home',
name: 'home',
@@ -32,39 +23,15 @@ const routes = [
meta: { title: '首页' },
children: [
{
path: 'aericletype/:type',
path: 'aericletype',
name: 'homeByType'
},
{
path: 'aericletitle/:title',
path: 'aericletitle',
name: 'homeByTitle'
}
]
},
// {
// path: '/home',
// name: 'home',
// component: HomePage,
// meta: {
// title: '首页'
// }
// },
// {
// path: '/home/aericletype/:type',
// name: 'homeByType',
// component: HomePage,
// meta: {
// title: '首页'
// }
// },
// {
// path: '/home/aericletitle/:title',
// name: 'homeByTitle',
// component: HomePage,
// meta: {
// title: '首页'
// }
// },
{
path: '/article-list',
name: 'articleList',

View File

@@ -84,7 +84,7 @@ class ArticleService {
* @returns {Promise}
*/
incrementArticleViews(id) {
return apiService.post(`/articles/${id}/views`)
return apiService.post(`/articles/view/${id}`)
}
/**

155
src/store/globalStore.js Normal file
View File

@@ -0,0 +1,155 @@
import { defineStore } from 'pinia'
/**
* 全局状态管理store
* 提供全局的传值和获取值的功能
* 任何页面都可以调用和获取其中的值
* 添加了localStorage持久化功能确保刷新页面后数据不会丢失
*/
export const useGlobalStore = defineStore('global', {
// 状态定义
state: () => {
// 从localStorage读取持久化的数据
const savedGlobalData = localStorage.getItem('globalStoreData')
const initialGlobalData = savedGlobalData ? JSON.parse(savedGlobalData) : {}
return {
// 全局数据对象,存储所有需要共享的数据
globalData: initialGlobalData,
// 可以在这里定义特定的状态属性,便于类型提示和直接使用
user: null,
loading: false,
notifications: []
}
},
// 计算属性 - 用于获取和转换状态
getters: {
/**
* 检查全局数据中是否存在指定的键
* @param {string} key - 要检查的键名
* @returns {boolean} - 如果存在返回true否则返回false
*/
hasValue: (state) => (key) => {
return Object.prototype.hasOwnProperty.call(state.globalData, key)
},
/**
* 获取指定键的值
* @param {string} key - 要获取的键名
* @returns {any} - 对应的值如果不存在则返回undefined
*/
getValue: (state) => (key) => {
return state.globalData[key]
},
/**
* 获取所有全局数据
* @returns {Object} - 所有全局数据
*/
getAllData: (state) => {
return { ...state.globalData }
}
},
// 操作方法 - 用于修改状态
actions: {
/**
* 设置全局数据
* @param {string} key - 键名
* @param {any} value - 要存储的值
*/
setValue(key, value) {
this.globalData[key] = value
// 持久化到localStorage
this._persistData()
},
/**
* 将数据持久化到localStorage的内部方法
* @private
*/
_persistData() {
try {
localStorage.setItem('globalStoreData', JSON.stringify(this.globalData))
} catch (error) {
console.error('Failed to persist data to localStorage:', error)
}
},
/**
* 批量设置多个键值对
* @param {Object} data - 包含多个键值对的对象
*/
setMultipleValues(data) {
if (typeof data === 'object' && data !== null) {
Object.assign(this.globalData, data)
// 持久化到localStorage
this._persistData()
}
},
/**
* 删除指定的全局数据
* @param {string} key - 要删除的键名
*/
removeValue(key) {
if (Object.prototype.hasOwnProperty.call(this.globalData, key)) {
delete this.globalData[key]
// 持久化到localStorage
this._persistData()
}
},
/**
* 清空所有全局数据
*/
clearAll() {
this.globalData = {}
// 清除localStorage中的数据
try {
localStorage.removeItem('globalStoreData')
} catch (error) {
console.error('Failed to clear data from localStorage:', error)
}
},
/**
* 设置用户信息
* @param {Object} userInfo - 用户信息对象
*/
setUser(userInfo) {
this.user = userInfo
},
/**
* 设置加载状态
* @param {boolean} status - 加载状态
*/
setLoading(status) {
this.loading = status
},
/**
* 添加通知
* @param {Object} notification - 通知对象
*/
addNotification(notification) {
this.notifications.push({
id: Date.now(),
...notification
})
},
/**
* 移除通知
* @param {number} id - 通知ID
*/
removeNotification(id) {
const index = this.notifications.findIndex(notification => notification.id === id)
if (index !== -1) {
this.notifications.splice(index, 1)
}
}
}
})

208
src/store/useExample.md Normal file
View File

@@ -0,0 +1,208 @@
# Pinia 全局状态管理使用示例
## 1. 基础使用方法
### 在任意组件中使用全局状态
```vue
<template>
<div>
<h2>全局状态管理示例</h2>
<!-- 显示全局数据 -->
<div v-if="globalStore.hasValue('exampleData')">
<p>从全局store获取的数据: {{ globalStore.getValue('exampleData') }}</p>
</div>
<div v-else>
<p>全局数据尚未设置</p>
</div>
<!-- 设置全局数据 -->
<el-input v-model="inputValue" placeholder="输入要存储的全局数据" />
<el-button @click="setGlobalData">设置全局数据</el-button>
<el-button @click="checkGlobalData">检查是否存在</el-button>
<el-button @click="clearGlobalData" type="danger">清空全局数据</el-button>
</div>
</template>
<script setup>
import { ref } from 'vue'
import { useGlobalStore } from '@/store/globalStore'
// 获取全局store实例
const globalStore = useGlobalStore()
const inputValue = ref('')
// 设置全局数据
const setGlobalData = () => {
globalStore.setValue('exampleData', inputValue.value)
ElMessage.success('数据已保存到全局状态')
}
// 检查数据是否存在
const checkGlobalData = () => {
if (globalStore.hasValue('exampleData')) {
ElMessage.info(`数据存在: ${globalStore.getValue('exampleData')}`)
} else {
ElMessage.warning('数据不存在')
}
}
// 清空全局数据
const clearGlobalData = () => {
globalStore.removeValue('exampleData')
ElMessage.success('数据已从全局状态中移除')
}
</script>
```
## 2. 页面间数据传递示例
### 页面A - 设置数据
```vue
<script setup>
import { useGlobalStore } from '@/store/globalStore'
import { useRouter } from 'vue-router'
const globalStore = useGlobalStore()
const router = useRouter()
const navigateToPageB = () => {
// 存储页面间需要传递的数据
globalStore.setValue('sharedData', {
id: 123,
name: '测试数据',
timestamp: Date.now()
})
// 跳转到页面B
router.push('/page-b')
}
</script>
```
### 页面B - 获取数据
```vue
<script setup>
import { onMounted } from 'vue'
import { useGlobalStore } from '@/store/globalStore'
const globalStore = useGlobalStore()
onMounted(() => {
// 检查并获取从页面A传递过来的数据
if (globalStore.hasValue('sharedData')) {
const data = globalStore.getValue('sharedData')
console.log('从页面A接收的数据:', data)
// 使用接收到的数据进行操作
}
})
</script>
```
## 3. 批量操作示例
```javascript
import { useGlobalStore } from '@/store/globalStore'
const globalStore = useGlobalStore()
// 批量设置多个键值对
globalStore.setMultipleValues({
appConfig: {
theme: 'dark',
language: 'zh-CN'
},
userPreferences: {
notifications: true,
fontSize: 16
},
lastUpdated: new Date().toISOString()
})
// 获取所有全局数据
const allData = globalStore.getAllData()
console.log('所有全局数据:', allData)
// 清空所有数据
globalStore.clearAll()
```
## 4. 用户状态管理示例
```vue
<template>
<div>
<div v-if="globalStore.user">
<h3>欢迎回来{{ globalStore.user.username }}</h3>
<el-button @click="logout">登出</el-button>
</div>
<div v-else>
<h3>请登录</h3>
<!-- 登录表单 -->
</div>
<!-- 加载状态指示器 -->
<el-loading v-loading="globalStore.loading" :text="'加载中...'">
<!-- 内容区域 -->
</el-loading>
</div>
</template>
<script setup>
import { useGlobalStore } from '@/store/globalStore'
const globalStore = useGlobalStore()
const login = async (credentials) => {
try {
// 设置加载状态
globalStore.setLoading(true)
// 模拟登录请求
const response = await authService.login(credentials)
// 保存用户信息到全局状态
globalStore.setUser(response.user)
// 添加登录成功通知
globalStore.addNotification({
type: 'success',
message: '登录成功!'
})
} catch (error) {
console.error('登录失败:', error)
} finally {
// 无论成功失败都清除加载状态
globalStore.setLoading(false)
}
}
const logout = () => {
// 清除用户信息
globalStore.setUser(null)
// 添加登出通知
globalStore.addNotification({
type: 'info',
message: '您已成功登出'
})
}
</script>
```
## 5. 注意事项
1. **数据持久化**默认情况下Pinia状态只在内存中存在页面刷新后会丢失。如果需要持久化可以考虑
- 使用localStorage/sessionStorage结合Pinia插件
- 使用Cookie存储关键信息
2. **性能考虑**:避免在全局状态中存储过大的数据,这可能会影响应用性能
3. **类型安全**如果使用TypeScript可以为store添加类型定义
4. **模块化**随着应用复杂度增加可以考虑将不同功能的数据分开存储到多个store中
5. **调试**Pinia提供了良好的开发工具支持可以通过Vue Devtools进行调试

View File

@@ -6,7 +6,7 @@
/* 内容区圆角 */
/* 首页 hero 区域高度和间距 */
--hero-height: 600px;
--hero-height: 768px;
/* hero 默认高度 */
--hero-height-small: 150px;
/* hero 收缩后高度 */
@@ -48,9 +48,9 @@
/* 分页区背景色 */
/* 导航栏样式 */
--nav-padding: 20px 40px;
--nav-padding: 15px 35px;
/* 导航栏默认内边距 */
--nav-padding-small: 15px 40px;
--nav-padding-small: 10px 25px;
/* 导航栏收缩后内边距 */
--nav-bg: rgba(145, 196, 238, 0.85);
/* 导航栏背景色 */
@@ -60,7 +60,8 @@
/* 导航栏隐藏时背景 */
--nav-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
/* 导航栏阴影 */
--nav-is-active: rgba(255, 0, 255, 0.5);
/* 导航栏激活项字体颜色 */
/* 字体颜色和菜单样式 */
--font-color-title: #AF7AC5;
/* 标题字体颜色 */
@@ -115,7 +116,7 @@ p {
width: 100%;
padding: var(--nav-padding);
z-index: 1000;
transition: all 0.4s ease;
transition: all 1s ease;
font-size: inherit;
/* display: flex; */
justify-content: space-between;
@@ -179,12 +180,21 @@ p {
.el-menu-demo .el-menu-item {
margin-left: 10px;
font-size: inherit;
color: rgba(255, 255, 255, .95);
}
.el-menu-demo .el-menu-item.is-active{
color: var(--nav-is-active);
}
/* 菜单项悬停和激活状态 */
.el-menu-item:hover,
.el-menu-item.is-active {
.el-menu-demo .el-menu-item:hover{
background-color: transparent;
color: rgba(255, 200, 255, 0.5);
opacity: 0.85;
}
.el-menu-demo .el-menu-item.is-active {
background-color: transparent;
color: var(--nav-is-active);
opacity: 0.85;
}
/* 去除菜单项悬停和激活时的背景色 */
@@ -379,6 +389,7 @@ p {
.RouterViewpage {
width: 100%;
margin-top: 11%;
}
.nonsensetitle {

View File

@@ -13,7 +13,7 @@ export interface Article {
categoryId: number
categoryName?: string
tags?: string
views?: number
viewCount?: number
commentCount?: number
articleid?: string
publishedAt?: string
@@ -31,7 +31,7 @@ export interface Message {
articleId?: number
parentId?: number
createdAt: string
replies?: Message[]
replyid?: number
time?: string
}

View File

@@ -17,30 +17,37 @@
<div class="about-skills">
<h3>前端技术栈</h3>
<div class="skills-list">
<el-tag type="primary">HTML5</el-tag>
<el-tag type="primary">CSS3</el-tag>
<el-tag type="primary">JavaScript</el-tag>
<el-tag type="primary">TypeScript</el-tag>
<el-tag type="primary">Vue.js</el-tag>
<el-tag type="primary">React</el-tag>
<el-tag type="primary">Node.js</el-tag>
<el-tag type="primary">Webpack</el-tag>
<el-tag type="primary">Git</el-tag>
<a href="https://developer.mozilla.org/zh-CN/docs/Web/HTML" target="_blank" class="skill-link"><el-tag type="primary">HTML5</el-tag></a>
<a href="https://developer.mozilla.org/zh-CN/docs/Web/CSS" target="_blank" class="skill-link"><el-tag type="primary">CSS3</el-tag></a>
<a href="https://tailwindcss.com/" target="_blank" class="skill-link"><el-tag type="primary">Tailwind CSS</el-tag></a>
<a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript" target="_blank" class="skill-link"><el-tag type="primary">JavaScript (ES6+)</el-tag></a>
<a href="https://www.typescriptlang.org/" target="_blank" class="skill-link"><el-tag type="primary">TypeScript</el-tag></a>
<a href="https://vuejs.org/" target="_blank" class="skill-link"><el-tag type="primary">Vue.js 3</el-tag></a>
<a href="https://pinia.vuejs.org/" target="_blank" class="skill-link"><el-tag type="primary">Pinia</el-tag></a>
<a href="https://react.dev/" target="_blank" class="skill-link"><el-tag type="primary">React 18</el-tag></a>
<a href="https://nodejs.org/" target="_blank" class="skill-link"><el-tag type="primary">Node.js</el-tag></a>
<a href="https://vite.dev/" target="_blank" class="skill-link"><el-tag type="primary">Vite</el-tag></a>
<a href="https://webpack.js.org/" target="_blank" class="skill-link"><el-tag type="primary">Webpack</el-tag></a>
<a href="https://element-plus.org/" target="_blank" class="skill-link"><el-tag type="primary">Element Plus</el-tag></a>
<a href="https://git-scm.com/" target="_blank" class="skill-link"><el-tag type="primary">Git</el-tag></a>
</div>
</div>
<div class="about-skills">
<h3>后端技术栈</h3>
<div class="skills-list">
<el-tag type="success">Spring Boot 2.6.13</el-tag>
<el-tag type="success">Spring Security</el-tag>
<el-tag type="success">Spring Data JPA</el-tag>
<el-tag type="success">MyBatis</el-tag>
<el-tag type="success">MySQL</el-tag>
<el-tag type="success">Lombok</el-tag>
<el-tag type="success">EHCache</el-tag>
<el-tag type="success">Maven</el-tag>
<el-tag type="success">Java 8</el-tag>
<a href="https://spring.io/projects/spring-boot" target="_blank" class="skill-link"><el-tag type="success">Spring Boot 3.x</el-tag></a>
<a href="https://spring.io/projects/spring-security" target="_blank" class="skill-link"><el-tag type="success">Spring Security</el-tag></a>
<a href="https://spring.io/projects/spring-data-jpa" target="_blank" class="skill-link"><el-tag type="success">Spring Data JPA</el-tag></a>
<a href="https://mybatis.org/mybatis-3/" target="_blank" class="skill-link"><el-tag type="success">MyBatis-Plus</el-tag></a>
<a href="https://www.mysql.com/" target="_blank" class="skill-link"><el-tag type="success">MySQL 8</el-tag></a>
<a href="https://www.postgresql.org/" target="_blank" class="skill-link"><el-tag type="success">PostgreSQL</el-tag></a>
<a href="https://redis.io/" target="_blank" class="skill-link"><el-tag type="success">Redis</el-tag></a>
<a href="https://projectlombok.org/" target="_blank" class="skill-link"><el-tag type="success">Lombok</el-tag></a>
<a href="https://mapstruct.org/" target="_blank" class="skill-link"><el-tag type="success">MapStruct</el-tag></a>
<a href="https://maven.apache.org/" target="_blank" class="skill-link"><el-tag type="success">Maven</el-tag></a>
<a href="https://gradle.org/" target="_blank" class="skill-link"><el-tag type="success">Gradle</el-tag></a>
<a href="https://www.oracle.com/java/technologies/java17.html" target="_blank" class="skill-link"><el-tag type="success">Java 17+</el-tag></a>
</div>
</div>
@@ -139,6 +146,20 @@ const goToMessageBoard = () => {
gap: 10px;
}
/* 技能链接样式 */
.skill-link {
text-decoration: none;
transition: transform 0.2s ease;
}
.skill-link:hover {
transform: translateY(-2px);
}
.skill-link:hover .el-tag {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
/* 兴趣爱好 */
.about-hobbies {
margin-bottom: 32px;

View File

@@ -26,9 +26,9 @@
<span class="badge badge-primary"> {{ categoryGroup.attributes.length }} </span>
<ul class="wp-block-list">
<li v-for="category in categoryGroup.attributes" :key="category.typeid">
<a class="btn" @click="handleCategoryClick(category.categoryid)"><kbd>{{ category.attributename
&nbsp;&nbsp;<a class="btn" @click="handleCategoryClick(category)"><kbd>{{ category.attributename
}}</kbd></a>
&nbsp; ({{ category.articles.length }})
&nbsp; ({{ category.articles.length }})
</li>
</ul>
</div>
@@ -50,7 +50,9 @@ import { ref, onMounted } from 'vue'
// 以下代码仅作示例,实际需根据 '@/services' 模块的真实导出调整
import { ElMessage } from 'element-plus'
import { categoryService, categoryAttributeService, articleService } from '@/services'
import { useGlobalStore } from '@/store/globalStore'
const globalStore = useGlobalStore()
const router = useRouter()
// 响应式状态
@@ -141,12 +143,14 @@ const getCategoryAttributes = async (processedCategories: any[]) => {
* 注意现在实际上使用的是属性ID而不是分类ID
* @param {string | number} attributeId - 属性ID
*/
const handleCategoryClick = (attributeId: string | number) => {
const handleCategoryClick = (attribute: any) => {
globalStore.setValue('attribute', {
id: attribute.typeid || attribute.categoryid,
name: attribute.attributename || attribute.typename || '未命名属性',
})
console.log(attribute)
router.push({
path: '/home/aericletype',
query: {
attributeId: String(attributeId)
}
})
}
@@ -192,7 +196,6 @@ onMounted(() => {
.category-group ul li {
display: flex;
align-items: center;
padding: 5px 0;
}
.category-group ul li .btn::before {
@@ -201,7 +204,6 @@ onMounted(() => {
.category-group ul li .btn:hover {
background-color: rgb(245, 247, 250, 0.7);
border-bottom: #4b64f0 2px solid;
}
.alert:not(.alert-secondary) {

View File

@@ -29,7 +29,7 @@
</span>
<span class="meta-item">
<i class="el-icon-view"></i>
{{ article.views || 0 }} 阅读
{{ article.viewCount || 0 }} 阅读
</span>
</div>
</div>
@@ -42,38 +42,24 @@
<!-- 文章底部 -->
<div class="article-footer">
<div class="tag-list">
<span
v-for="tag in article.tags || []"
:key="tag"
class="el-tag el-tag--primary"
>
<span v-for="tag in article.tags || []" :key="tag" class="el-tag el-tag--primary">
{{ tag }}
</span>
</div>
<!-- 文章操作 -->
<div class="article-actions">
<el-button
type="primary"
icon="el-icon-arrow-left"
@click="goBack"
plain
>
<el-button type="primary" icon="el-icon-arrow-left" @click="goBack" plain>
返回
</el-button>
</div>
</div>
<!-- 相关文章 -->
<div class="related-articles" v-if="relatedArticles.length > 0">
<h3>相关文章</h3>
<div class="related-articles-list">
<div
v-for="item in relatedArticles"
:key="item.id"
class="related-article-item"
@click="handleRelatedArticleClick(item.id)"
>
<div v-for="item in relatedArticles" :key="item.id" class="related-article-item"
@click="handleRelatedArticleClick(item.id)">
<i class="el-icon-document"></i>
<span>{{ item.title }}</span>
</div>
@@ -85,7 +71,13 @@
<div v-else class="empty-container">
<el-empty description="文章不存在" />
</div>
<!-- 评论区 -->
<div>
<messageboard class="message-board" v-if="article && Object.keys(article).length > 0" v-model:comments="article.articleid" />
</div>
</div>
</template>
<script setup lang="ts">
@@ -95,6 +87,7 @@ import { articleService } from '@/services'
import { ElMessage } from 'element-plus'
import type { Article } from '@/types'
import { formatDate } from '@/utils/dateUtils'
import messageboard from './messageboard.vue'
const route = useRoute()
const router = useRouter()
@@ -131,10 +124,10 @@ const fetchArticleDetail = async () => {
await articleService.incrementArticleViews(Number(articleId))
console.log('文章浏览量增加成功')
// 更新前端显示的浏览量
if (article.value.views) {
article.value.views++
if (article.value.viewCount) {
article.value.viewCount++
} else {
article.value.views = 1
article.value.viewCount = 1
}
} catch (err) {
console.error('增加文章浏览量失败:', err)
@@ -380,6 +373,7 @@ onMounted(() => {
gap: 8px;
}
}
/* 文章内容 */
.article-content {
font-size: 1.05rem;
@@ -464,7 +458,10 @@ onMounted(() => {
border-radius: 12px;
text-align: center;
}
/* 评论区 */
.message-board {
margin-top: 32px;
}
/* 响应式设计 */
@media (max-width: 768px) {
#article-container {

View File

@@ -1,260 +0,0 @@
<template>
<div class="comment-demo-container">
<h1>嵌套留言Demo</h1>
<!-- 留言列表 -->
<div class="comments-wrapper">
<div v-if="loading" class="loading">加载中...</div>
<div v-else-if="commentTree.length === 0" class="empty">暂无留言</div>
<div v-else class="comment-list">
<!-- 递归渲染留言树 -->
<CommentItem v-for="comment in commentTree" :key="comment.id" :comment="comment" />
</div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted, defineComponent, h } from 'vue'
// 模拟留言数据
const mockComments = [
{
id: 'a',
content: '这是主留言A',
parentId: null,
author: '用户A',
createdAt: new Date().toISOString()
},
{
id: 'b',
content: '这是回复A的留言B',
parentId: 'a',
author: '用户B',
createdAt: new Date(Date.now() + 1000 * 60 * 5).toISOString() // 5分钟后
},
{
id: 'c',
content: '这是回复B的留言C',
parentId: 'b',
author: '用户C',
createdAt: new Date(Date.now() + 1000 * 60 * 10).toISOString() // 10分钟后
},
{
id: 'd',
content: '这是另一个主留言D',
parentId: null,
author: '用户D',
createdAt: new Date(Date.now() + 1000 * 60 * 15).toISOString() // 15分钟后
},
{
id: 'e',
content: '这是回复D的留言E',
parentId: 'd',
author: '用户E',
createdAt: new Date(Date.now() + 1000 * 60 * 20).toISOString() // 20分钟后
},
{
id: 'f',
content: '这是回复A的另一条留言F',
parentId: 'a',
author: '用户F',
createdAt: new Date(Date.now() + 1000 * 60 * 25).toISOString() // 25分钟后
},
{
id: 'g',
content: '这是回复C的留言G三级嵌套',
parentId: 'c',
author: '用户G',
createdAt: new Date(Date.now() + 1000 * 60 * 30).toISOString() // 30分钟后
}
]
// 响应式状态
const loading = ref(false)
const commentTree = ref([])
// 递归构建评论树结构的函数
const buildCommentTree = (comments) => {
// 创建评论ID到评论对象的映射方便快速查找
const commentMap = {}
comments.forEach(comment => {
commentMap[comment.id] = { ...comment, children: [] }
})
// 构建树结构
const roots = []
comments.forEach(comment => {
if (!comment.parentId) {
// 没有parentId的是根节点
roots.push(commentMap[comment.id])
} else {
// 有parentId的是子节点添加到父节点的children数组中
if (commentMap[comment.parentId]) {
commentMap[comment.parentId].children.push(commentMap[comment.id])
}
}
})
return roots
}
// 获取留言数据
const fetchComments = async () => {
try {
loading.value = true
// 模拟异步请求
await new Promise(resolve => setTimeout(resolve, 500))
// 处理数据,构建树结构
commentTree.value = buildCommentTree(mockComments)
console.log('构建的留言树:', commentTree.value)
} catch (error) {
console.error('获取留言失败:', error)
} finally {
loading.value = false
}
}
// 留言项组件(递归组件)
const CommentItem = defineComponent({
name: 'CommentItem',
props: {
comment: {
type: Object,
required: true
}
},
setup(props) {
// 格式化日期
const formatDate = (dateString) => {
const date = new Date(dateString)
return date.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
})
}
return () => h('div', { class: 'comment-item' }, [
h('div', { class: 'comment-header' }, [
h('span', { class: 'comment-author' }, props.comment.author),
h('span', { class: 'comment-time' }, formatDate(props.comment.createdAt))
]),
h('div', { class: 'comment-content' }, props.comment.content),
// 递归渲染子留言
props.comment.children && props.comment.children.length > 0 ?
h('div', { class: 'comment-children' },
props.comment.children.map(comment =>
h(CommentItem, { key: comment.id, comment })
)
) : null
])
}
})
// 组件挂载时获取数据
onMounted(() => {
fetchComments()
})
</script>
<style scoped>
.comment-demo-container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
}
h1 {
text-align: center;
color: #333;
margin-bottom: 30px;
}
.comments-wrapper {
background-color: #f9f9f9;
border-radius: 8px;
padding: 20px;
}
.loading,
.empty {
text-align: center;
padding: 40px;
color: #666;
}
.comment-list {
display: flex;
flex-direction: column;
gap: 20px;
}
.comment-item {
background-color: white;
border-radius: 8px;
padding: 16px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
transition: box-shadow 0.3s ease;
}
.comment-item:hover {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
.comment-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.comment-author {
font-weight: 600;
color: #333;
}
.comment-time {
font-size: 14px;
color: #999;
}
.comment-content {
color: #555;
line-height: 1.6;
word-break: break-word;
}
.comment-children {
margin-top: 16px;
margin-left: 30px;
padding-top: 16px;
border-top: 1px solid #eee;
display: flex;
flex-direction: column;
gap: 12px;
}
/* 响应式设计 */
@media (max-width: 768px) {
.comment-demo-container {
padding: 10px;
}
.comments-wrapper {
padding: 15px;
}
.comment-children {
margin-left: 15px;
}
}
</style>

View File

@@ -12,19 +12,18 @@
<div
class="article-card"
v-for="item in datas"
:key="item.id || (item.title + item.publishedAt)"
@click="handleArticleClick(item.articleid)"
:key="item.articleid"
@click="handleArticleClick(item)"
>
<h2 class="article-title">{{ item.title }}</h2>
<div class="article-meta">
<span class="article-author">{{ item.author || '清疯不颠' }}</span>
<span class="article-date">{{ formatDateDisplay(item.publishedAt || item.createTime) }}</span>
<span v-if="item.categoryName" class="article-category">{{ item.categoryName }}</span>
<span v-if="item.views" class="article-views">{{ item.views }} 阅读</span>
<span v-if="item.commentCount" class="article-comments">{{ item.commentCount }} 评论</span>
</div>
<div v-if="item.mg" class="article-tag">mg</div>
<p class="article-preview">{{ formatContentPreview(item.content, 150) }}</p>
<div class="article-meta">
<span class="article-date">{{ formatDateDisplay(item.createdAt || item.createTime) }}</span>
<span v-if="item.viewCount" class="article-views">{{ item.viewCount }} 阅读</span>
<span v-if="item.likes" class="article-likes">{{ item.likes }} 点赞</span>
<span v-if="item.messageCount" class="article-comments">{{ item.messageCount }} 评论</span>
</div>
</div>
</transition-group>
@@ -42,7 +41,9 @@ import { articleService } from '@/services'
import { formatDate, formatRelativeTime } from '@/utils/dateUtils'
import { formatContentPreview } from '@/utils/stringUtils'
import { ElMessage } from 'element-plus'
import { messageService } from '@/services'
import { useGlobalStore } from '@/store/globalStore'
const globalStore = useGlobalStore()
// 路由实例
const router = useRouter()
const route = useRoute()
@@ -63,33 +64,40 @@ const fetchArticles = async () => {
let res = {} // 使用let而不是const
// 检查URL参数
const query = route.query
const params = route.params
const localhome = route.path.split('/')[2];
// 优先使用attributeId参数新接口
if (query.attributeId) {
console.log('根据属性ID获取文章列表')
res = await articleService.getArticlesByAttribute(query.attributeId)
}
// 兼容旧的type参数
else if (params.type) {
console.log('根据类型ID获取文章列表兼容模式')
res = await articleService.getArticlesByCategory(params.type)
if (localhome==='aericletype') {
const data = globalStore.getValue('attribute')
res = await articleService.getArticlesByAttributeId(data.id)
}
// 搜索标题
else if (params.title || query.title) {
const title = params.title || query.title
console.log('根据标题获取文章列表')
res = await articleService.getArticlesByTitle(title)
else if (localhome==='aericletitle') {
const data = globalStore.getValue('title')
res = await articleService.getArticlesByTitle(data.title)
}
// 获取所有文章
else {
res = await articleService.getAllArticles()
console.log('获取所有文章列表')
res = await articleService.getAllArticles()
}
// 获取每个文章的留言数量
for (const item of res.data) {
try {
const msgRes = await messageService.getMessagesByArticleId(item.articleid)
if (msgRes && msgRes.data) {
item.messageCount = msgRes.data.length
} else {
item.messageCount = 0
}
} catch (err) {
console.error(`获取文章${item.articleid}留言数量失败:`, err)
item.messageCount = 0
}
}
// 修复使用正确的属性名data而不是date
console.log(res.data)
datas.value = res.data || []
console.log('获取文章列表成功:', datas.value)
} catch (error) {
console.error('获取文章列表失败:', error)
ElMessage.error('获取文章列表失败,请稍后重试')
@@ -105,9 +113,13 @@ const fetchArticles = async () => {
*/
const handleArticleClick = (article) => {
console.log('文章点击:', article)
globalStore.setValue('articlebutn', {
id: article.articleid,
name: article.title || '未命名文章',
})
router.push({
path: '/article/:url',
query: { url: article }
query: { url: article.articleid }
})
}
@@ -118,7 +130,6 @@ const handleArticleClick = (article) => {
*/
const formatDateDisplay = (dateString) => {
if (!dateString) return ''
try {
// 如果是今天或昨天的文章,显示相对时间
const date = new Date(dateString)

View File

@@ -10,116 +10,41 @@
</div>
<!-- 留言列表 -->
<transition-group name="message-item" tag="div" v-else>
<!-- 留言板留言 (articleid为空的留言) -->
<div v-if="messageBoardData.length > 0" class="message-section">
<h4>留言板留言</h4>
<!-- 主留言和回复树结构 -->
<div v-for="mainMsg in messageBoardData" :key="mainMsg.id" class="message-tree">
<!-- 主留言 -->
<div class="message-item" @mouseenter="hoverId = mainMsg.id" @mouseleave="hoverId = null">
<div class="message-avatar-container">
<img :src="getAvatar(mainMsg.email)" alt="头像" class="message-avatar" />
<div class="comment-list">
<div v-for="comment in messageBoardData" :key="comment.messageid" class="comment-item">
<div class="comment-header">
<!-- <img :src="getAvatar(comment.nickname)" :alt="" class="avatar"> -->
<img :src="getAvatar()" class="avatar">
<div class="user-info">
<div class="username">{{ comment.displayName || comment.nickname }}</div>
<div class="time">{{ comment.createdAt || '刚刚' }}</div>
</div>
<div class="message-content-container">
<div class="message-item-top">
<div class="message-nickname">{{ mainMsg.nickname || '匿名用户' }}</div>
<div class="message-time">{{ formatRelativeTime(mainMsg.createdAt) }}</div>
</div>
<div class="message-content">{{ mainMsg.content }}</div>
<!-- 回复按钮 -->
<div class="message-item-bottom">
<button class="reply-btn" @click="handleReply(mainMsg)"
:class="{ visible: hoverId === mainMsg.id }">
回复
</button>
<div class="comment-content" v-html="comment.content"></div>
<div class="comment-actions">
<!-- <span v-if="comment.likes" class="likes">{{ comment.likes }} </span> -->
<span class="reply-btn" @click="handleReply(null, comment)">回复</span>
</div>
<!-- 回复列表 -->
<div v-if="mainMsg.replies.length> 0" class="replies">
<div v-for="reply in mainMsg.replies" :key="reply.id" class="reply-item">
<div class="message-avatar-container">
<img :src="getAvatar(reply.email)" alt="头像" class="message-avatar" />
</div>
<div class="message-content-container">
<div class="message-item-top">
<div class="message-nickname">{{ reply.nickname || '匿名用户' }}</div>
<div class="message-time">{{ formatRelativeTime(reply.createdAt) }}
<div v-if="comment.replies && comment.replies && comment.replies.length > 0" class="reply-list">
<div v-for="reply in comment.replies" :key="reply.messageid" class="reply-item">
<div class="reply-header">
<img :src="getAvatar()" class="avatar">
<div class="user-info">
<div class="username">{{ reply.displayName || reply.nickname }}</div>
<div class="time">{{ reply.createdAt || '刚刚' }}</div>
</div>
</div>
<div class="message-content">
<span class="reply-to">@{{ mainMsg.nickname || '匿名用户' }}</span>
{{ reply.content }}
<div class="reply-content">{{ reply.content }}</div>
<div class="reply-actions">
<span class="reply-btn" @click="handleReply(comment, reply)">回复</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- 文章相关留言 (articleid不为空的留言) -->
<div v-if="articleRelatedData.length > 0" class="message-section">
<h4>文章留言</h4>
<div v-for="articleGroup in articleRelatedData" :key="articleGroup.articleId"
class="article-message-group">
<div class="article-message-header">
<span class="article-title">{{ articleGroup.articleTitle }}</span>
</div>
<div class="article-message-content">
<div v-for="mainMsg in articleGroup.messages" :key="mainMsg.messageid" class="message-tree">
<!-- 主留言 -->
<div class="message-item" @mouseenter="hoverId = mainMsg.messageid"
@mouseleave="hoverId = null">
<div class="message-avatar-container">
<img :src="getAvatar(mainMsg.email)" alt="头像" class="message-avatar" />
</div>
<div class="message-content-container">
<div class="message-item-top">
<div class="message-nickname">{{ mainMsg.nickname || '匿名用户' }}</div>
<div class="message-time">{{ formatRelativeTime(mainMsg.createdAt) }}
</div>
</div>
<div class="message-content">{{ mainMsg.content }}</div>
<!-- 回复按钮 -->
<div class="message-item-bottom">
<button class="reply-btn" @click="handleReply(mainMsg)"
:class="{ visible: hoverId === mainMsg.messageid }">
回复
</button>
</div>
<!-- 回复列表 -->
<div v-if="mainMsg.replies && mainMsg.replies.length" class="replies">
<div v-for="reply in mainMsg.replies" :key="reply.messageid"
class="reply-item">
<div class="message-avatar-container">
<img :src="getAvatar(reply.email)" alt="头像"
class="message-avatar" />
</div>
<div class="message-content-container">
<div class="message-item-top">
<div class="message-nickname">{{ reply.nickname || '匿名用户' }}
</div>
<div class="message-time">{{
formatRelativeTime(reply.createdAt) }}</div>
</div>
<div class="message-content">
<span class="reply-to">@{{ mainMsg.nickname || '匿名用户'
}}</span>
{{ reply.content }}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</transition-group>
<div v-if="!loading && messageBoardData.length === 0 && articleRelatedData.length === 0"
<!-- 无留言提示 -->
<div v-if="!loading && messageBoardData.length === 0 "
class="message-empty">
还没有留言快来抢沙发吧
</div>
@@ -137,20 +62,33 @@
</div>
<button class="reply-cancel-btn" @click="cancelReply">取消回复</button>
</div>
<el-form :model="form" label-width="0">
<el-form-item>
<el-form :model="form" :rules="rules" ref="formRef" label-width="0">
<el-form-item prop="content">
<el-input v-model="form.content" placeholder="评论内容" type="textarea" rows="4" clearable
:disabled="submitting" />
</el-form-item>
<div class="form-input-row">
<el-form-item>
<el-form-item prop="nickname">
<el-input v-model="form.nickname" placeholder="昵称" clearable :disabled="submitting" />
</el-form-item>
<el-form-item>
<el-form-item prop="email">
<el-input v-model="form.email" placeholder="邮箱/QQ号" clearable :disabled="submitting" />
</el-form-item>
<el-form-item>
<el-input v-model="form.captcha" placeholder="验证码" clearable :disabled="submitting" />
<el-form-item prop="captcha">
<div class="captcha-container">
<el-input
v-model="form.captcha"
placeholder="验证码"
clearable
:disabled="submitting"
@focus="showCaptchaHint = true"
@blur="showCaptchaHint = false"
/>
<div class="captcha-hint" @click="generateCaptcha" v-show="showCaptchaHint">
{{ captchaHint }}
<span class="refresh-icon"></span>
</div>
</div>
</el-form-item>
</div>
<div class="form-input-row">
@@ -170,17 +108,107 @@
<script setup>
import { reactive, ref, onMounted } from 'vue'
import { messageService } from '@/services'
import { formatRelativeTime } from '@/utils/dateUtils'
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'
const route = useRoute()
const hoverId = ref(null)
import { ElMessage, ElForm } from 'element-plus'
import { useGlobalStore } from '@/store/globalStore'
const globalStore = useGlobalStore()
const messageBoardData = ref([]) // 留言板留言articleid为空的主留言及其回复
const articleRelatedData = 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: ''
})
// 生成简单验证码
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' },
{ min: 1, max: 500, message: '评论内容长度应在1-500个字符之间', trigger: 'blur' }
],
nickname: [
{ required: true, message: '请输入昵称', trigger: 'blur' },
{ min: 2, max: 20, message: '昵称长度应在2-20个字符之间', trigger: 'blur' }
],
email: [
{ required: true, message: '请输入邮箱/QQ号', trigger: 'blur' },
{
validator: (rule, value, callback) => {
// 验证邮箱格式或QQ号格式5-11位数字
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const qqRegex = /^[1-9]\d{4,10}$/;
if (emailRegex.test(value) || qqRegex.test(value)) {
callback();
} else {
callback(new Error('请输入有效的邮箱地址或QQ号'));
}
},
trigger: 'blur'
}
],
captcha: [
{ required: true, message: '请输入验证码', trigger: 'blur' },
{
validator: (rule, value, callback) => {
if (value.toLowerCase() !== captchaAnswer.value) {
callback(new Error('验证码错误,请重新输入'))
} else {
callback()
}
},
trigger: 'blur'
}
]
}
// 生成头像URL
const getAvatar = (email) => {
@@ -192,17 +220,40 @@ const getAvatar = (email) => {
const fetchMessages = async () => {
try {
loading.value = true
const res = await messageService.getAllMessages()
const allMessages = res.data || []
// 按articleId和parentId分类留言
const boardMsgs = []
const articleMsgsMap = new Map()
let res = null
// 首先处理所有留言
// 安全获取文章ID如果globalStore中没有articlebutn则返回null
const articleData = globalStore.getValue('articlebutn')
const articleid = (articleData && typeof articleData === 'object' && 'id' in articleData) ? articleData.id : null
form.articleid = articleid
// 根据是否有文章ID选择不同的API调用
if (articleid) {
res = await messageService.getMessagesByArticleId(articleid)
console.log(`获取文章ID=${articleid}的相关留言列表`)
} else {
res = await messageService.getAllMessages()
// 过滤掉articleid不为空的留言只保留articleid为空或不存在的留言
if (res && res.data) {
res.data = res.data.filter(msg => !msg.articleid || msg.articleid === '')
}
}
// 验证响应结果
if (!res || !res.data) {
console.warn('未获取到留言数据')
messageBoardData.value = []
return
}
const allMessages = res.data
// 处理所有留言为主留言添加replies数组
const allMessagesWithReplies = allMessages.map(msg => ({
...msg,
replies: []
}))
// 分离主留言和回复
const mainMessages = []
const replies = []
@@ -214,55 +265,55 @@ const fetchMessages = async () => {
mainMessages.push(msg)
}
})
// 将回复添加到对应的主留言中
replies.forEach(reply => {
// 找到父留言
const parentMsg = mainMessages.find(msg => msg.messageid === reply.parentid)
console.log('找到的父留言:', mainMessages)
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)
}
})
// 按articleId分类主留言
mainMessages.forEach(msg => {
if (msg.articleid) {
// 文章相关留言
if (!articleMsgsMap.has(msg.articleid)) {
articleMsgsMap.set(msg.articleid, [])
}
articleMsgsMap.get(msg.articleid).push(msg)
} else {
// 留言板留言
boardMsgs.push(msg)
}
})
// 转换文章留言Map为数组
articleRelatedData.value = Array.from(articleMsgsMap.entries()).map(([articleId, msgs]) => ({
articleId,
articleTitle: `文章 ${articleId}`, // 这里可以根据需要从其他地方获取文章标题
messages: msgs
}))
console.log('主留言和回复分离:', { mainMessages, replies })
messageBoardData.value = boardMsgs
console.log('获取留言列表成功:', { boardMessages: messageBoardData.value, articleMessages: articleRelatedData.value })
// 更新留言板数据
messageBoardData.value = mainMessages
} catch (error) {
console.error('获取留言列表失败:', error)
ElMessage.error('获取留言失败,请稍后重试')
messageBoardData.value = [] // 出错时清空数据,避免显示错误内容
} finally {
loading.value = false
console.log('留言列表加载完成,共有' + messageBoardData.value.length + '条留言板留言')
}
}
// 处理回复
const handleReply = (msg) => {
replyingTo.value = {
id: msg.messageid,
nickname: msg.nickname || '匿名用户',
content: msg.content
}
const handleReply = (msg, reply) => {
// 检查是否是回复模式
if (msg !== null) {
// 回复模式
form.replyid = reply.messageid
form.parentid = msg.messageid
form.content = `@${replyingTo.value.nickname} `
} else {
// 普通回复模式
form.replyid = null
form.parentid = reply.messageid
}
replyingTo.value = {
id: reply.messageid,
nickname: reply.nickname || '匿名用户',
content: reply.content
}
// 滚动到输入框
setTimeout(() => {
document.querySelector('.message-form-section')?.scrollIntoView({ behavior: 'smooth' })
@@ -279,33 +330,39 @@ const cancelReply = () => {
// 组件挂载时获取留言列表
onMounted(() => {
fetchMessages()
generateCaptcha() // 页面加载时生成验证码
})
const form = reactive({
parentid: null,
content: '',
nickname: '',
email: '',
})
const onSubmit = async () => {
if (!form.content || !form.nickname) return
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.replyid) {
if (form.parentid) {
// 回复模式
const res = await messageService.saveMessage({
content: form.content,
nickname: form.nickname,
email: form.email,
parentid: form.replyid
parentid: form.parentid,
replyid: form.replyid,
articleid: form.articleid
})
if (res.success) {
ElMessage.success('回复成功')
fetchMessages() // 重新获取列表
resetForm()
cancelReply()
} else {
ElMessage.error('回复失败:' + (res.message || '未知错误'))
@@ -316,7 +373,7 @@ const onSubmit = async () => {
content: form.content,
nickname: form.nickname,
email: form.email,
captcha: form.captcha
articleid: form.articleid
})
if (res.success) {
@@ -342,6 +399,8 @@ const resetForm = () => {
form.nickname = ''
form.email = ''
form.captcha = ''
form.parentid = null
form.articleid = null
replyingTo.value = { id: null, nickname: '', content: '' }
}
@@ -443,19 +502,6 @@ const post_comment_reply_cancel = () => {
justify-content: flex-end;
}
.reply-btn {
background: none;
border: none;
color: #3498db;
cursor: pointer;
font-size: 0.85rem;
opacity: 0;
transition: opacity 0.3s ease;
}
.reply-btn.visible {
opacity: 1;
}
.reply-btn:hover {
color: #2980b9;
@@ -469,9 +515,8 @@ const post_comment_reply_cancel = () => {
}
.reply-item {
display: flex;
margin-bottom: 15px;
padding: 10px;
/* padding: 10px; */
background-color: rgba(255, 255, 255, 0.7);
border-radius: 6px;
}
@@ -640,23 +685,6 @@ const post_comment_reply_cancel = () => {
text-align: center;
}
.reply-btn {
background: #409eff;
color: #fff;
border: none;
border-radius: 6px;
padding: 4px 12px;
margin-top: 4px;
transition: background 0.2s;
float: right;
visibility: hidden;
/* 默认隐藏但占位 */
}
.message-item:hover .reply-btn,
.reply-btn.visible {
visibility: visible;
}
.message-empty {
color: #bbb;
@@ -742,6 +770,146 @@ const post_comment_reply_cancel = () => {
transform: translateY(20px);
}
.comment-list {
background-color: #f5f5f5;
}
.comment-item {
background-color: #fff;
padding: 16px;
margin-bottom: 16px;
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.comment-header {
display: flex;
align-items: center;
margin-bottom: 12px;
}
.avatar {
width: 40px;
height: 40px;
border-radius: 50%;
margin-right: 12px;
}
.user-info {
flex: 1;
text-align: left;
}
.username {
font-weight: bold;
font-size: 14px;
margin-bottom: 4px;
}
.time {
font-size: 12px;
color: #999;
}
.comment-content {
font-size: 14px;
line-height: 1.6;
margin-bottom: 12px;
word-break: break-word;
}
/* 验证码相关样式 */
.captcha-container {
position: relative;
width: 100%;
}
.captcha-hint {
position: absolute;
top: -30px;
right: 0;
background-color: #f0f9ff;
border: 1px solid #d9ecff;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
color: #1890ff;
white-space: nowrap;
z-index: 10;
cursor: pointer;
display: flex;
align-items: center;
gap: 5px;
transition: all 0.3s;
}
.captcha-hint:hover {
background-color: #e6f7ff;
border-color: #91d5ff;
}
.refresh-icon {
font-size: 14px;
display: inline-block;
transition: transform 0.3s;
}
.captcha-hint:hover .refresh-icon {
transform: rotate(180deg);
}
.comment-actions {
text-align: right;
gap: 20px;
font-size: 14px;
color: #666;
}
.comment-actions .likes {
margin-right: 86%;
}
.likes,
.reply-btn {
cursor: pointer;
&:hover {
color: #409eff;
}
}
.reply-list {
margin-top: 16px;
padding-left: 52px;
border-top: 1px solid #f0f0f0;
padding-top: 16px;
}
.reply-item {
background-color: #fafafa;
padding: 12px;
margin-bottom: 8px;
border-radius: 6px;
}
.reply-header {
display: flex;
align-items: center;
margin-bottom: 8px;
}
.reply-content {
font-size: 14px;
line-height: 1.5;
margin-bottom: 8px;
}
.reply-actions {
font-size: 12px;
color: #666;
text-align: right;
}
@media (max-width: 768px) {
.message-board {
padding: 8px 0;