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

@@ -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>
<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="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-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>
<!-- 回复列表 -->
<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>
</div>
<div class="message-content">
<span class="reply-to">@{{ mainMsg.nickname || '匿名用户' }}</span>
{{ reply.content }}
</div>
</div>
</div>
</div>
<div class="reply-content">{{ reply.content }}</div>
<div class="reply-actions">
<span class="reply-btn" @click="handleReply(comment, reply)">回复</span>
</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>
<!-- 无留言提示 -->
<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,21 +220,44 @@ 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 = []
allMessagesWithReplies.forEach(msg => {
if (msg.parentid && msg.parentid > 0) {
replies.push(msg)
@@ -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
} else {
// 普通回复模式
form.replyid = null
form.parentid = reply.messageid
}
replyingTo.value = {
id: reply.messageid,
nickname: reply.nickname || '匿名用户',
content: reply.content
}
form.parentid = msg.messageid
form.content = `@${replyingTo.value.nickname} `
// 滚动到输入框
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;