feat: 重构留言板功能并优化UI样式

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

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

优化移动端响应式布局,改进留言表单验证逻辑。新增留言相关文章显示功能,完善用户头像生成逻辑。调整首页文章卡片样式,增加阅读量、点赞数和评论数显示。
This commit is contained in:
qingfeng1121
2025-10-22 13:28:47 +08:00
parent b042e2a511
commit 5b3fba7bfb
16 changed files with 1336 additions and 627 deletions

View File

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

868
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -13,11 +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"
},
@@ -26,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,7 +10,7 @@
</div>
<div id="cont">
<div class="cont1">
<h2>小颠片刻</h2>
<h3>小颠片刻</h3>
<p>左眼右右眼左四十五度成就美</p>
</div>
<div class="cont2">
@@ -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;
}

View File

@@ -129,6 +129,7 @@ const startTypewriter = () => {
* 菜单选择跳转
*/
const handleSelect = (key: string) => {
globalStore.clearAll()
router.push({ path: '/' + key });
};

View File

@@ -2,15 +2,28 @@ 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',
@@ -41,30 +32,6 @@ const routes = [
}
]
},
// {
// 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}`)
}
/**

View File

@@ -4,17 +4,24 @@ import { defineStore } from 'pinia'
* 全局状态管理store
* 提供全局的传值和获取值的功能
* 任何页面都可以调用和获取其中的值
* 添加了localStorage持久化功能确保刷新页面后数据不会丢失
*/
export const useGlobalStore = defineStore('global', {
// 状态定义
state: () => ({
state: () => {
// 从localStorage读取持久化的数据
const savedGlobalData = localStorage.getItem('globalStoreData')
const initialGlobalData = savedGlobalData ? JSON.parse(savedGlobalData) : {}
return {
// 全局数据对象,存储所有需要共享的数据
globalData: {},
globalData: initialGlobalData,
// 可以在这里定义特定的状态属性,便于类型提示和直接使用
user: null,
loading: false,
notifications: []
}),
}
},
// 计算属性 - 用于获取和转换状态
getters: {
@@ -54,6 +61,20 @@ export const useGlobalStore = defineStore('global', {
*/
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)
}
},
/**
@@ -63,6 +84,8 @@ export const useGlobalStore = defineStore('global', {
setMultipleValues(data) {
if (typeof data === 'object' && data !== null) {
Object.assign(this.globalData, data)
// 持久化到localStorage
this._persistData()
}
},
@@ -73,6 +96,8 @@ export const useGlobalStore = defineStore('global', {
removeValue(key) {
if (Object.prototype.hasOwnProperty.call(this.globalData, key)) {
delete this.globalData[key]
// 持久化到localStorage
this._persistData()
}
},
@@ -81,6 +106,12 @@ export const useGlobalStore = defineStore('global', {
*/
clearAll() {
this.globalData = {}
// 清除localStorage中的数据
try {
localStorage.removeItem('globalStoreData')
} catch (error) {
console.error('Failed to clear data from localStorage:', error)
}
},
/**

View File

@@ -389,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

@@ -19,12 +19,16 @@
<div class="skills-list">
<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://developer.mozilla.org/zh-CN/docs/Web/JavaScript" target="_blank" class="skill-link"><el-tag type="primary">JavaScript</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</el-tag></a>
<a href="https://react.dev/" target="_blank" class="skill-link"><el-tag type="primary">React</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>
@@ -32,15 +36,18 @@
<div class="about-skills">
<h3>后端技术栈</h3>
<div class="skills-list">
<a href="https://spring.io/projects/spring-boot" target="_blank" class="skill-link"><el-tag type="success">Spring Boot 2.6.13</el-tag></a>
<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</el-tag></a>
<a href="https://www.mysql.com/" target="_blank" class="skill-link"><el-tag type="success">MySQL</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://www.ehcache.org/" target="_blank" class="skill-link"><el-tag type="success">EHCache</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://www.oracle.com/java/technologies/java8.html" target="_blank" class="skill-link"><el-tag type="success">Java 8</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>

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

@@ -13,17 +13,17 @@
class="article-card"
v-for="item in datas"
:key="item.articleid"
@click="handleArticleClick(item.articleid)"
@click="handleArticleClick(item)"
>
<h2 class="article-title">{{ item.title }}</h2>
<div class="article-meta">
<!-- <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.viewCount" class="article-views">{{ item.views }} 阅读</span>
<!-- <span v-if="item.content" 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>
@@ -41,8 +41,8 @@ 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()
@@ -81,11 +81,23 @@ const fetchArticles = async () => {
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)
console.log(res.data)
datas.value = res.data || []
console.log('文章数据已赋值:', datas.value)
} catch (error) {
console.error('获取文章列表失败:', error)
ElMessage.error('获取文章列表失败,请稍后重试')
@@ -101,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 }
})
}
@@ -114,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;