目录
一、成果概述
给日志添加了评论及回复功能,并且只有评论发布者本人可以删除自己的评论,而其他人只能回复,实现了简单的交互功能。
二、关键代码
1.数据库设计
由于回复功能涉及到级联顺序,所以需要加入pid属性,记录评论的上级评论;同时为了找到根评论,设置origin_id属性,方便后续遍历,按顺序排列各个评论。
2.前端排版
<!--评论列表-->
<div>
<div v-for="item in comments" :key="item.id" style="border-bottom: 1px solid #ccc; padding: 10px 0; ">
<div style="display: flex">
<div style="width: 100px; text-align: center">
<el-image :src="item.headPortrait" style="width: 50px; height: 50px; border-radius: 50%"></el-image>
</div> <!-- 头像-->
<div style="flex: 1; font-size: 14px; padding: 5px 0; line-height: 25px">
<b>{{ item.username }}:</b>
<span>{{ item.content }}</span>
<div style="display: flex; line-height: 20px; margin-top: 5px">
<div style="width: 200px;">
<el-icon><Clock /></el-icon><span style="margin-left: 5px">{{ item.time }}</span>
</div>
<div style="text-align: right; flex: 1">
<el-button style="margin-left: 5px" type="text" @click="handleReply(item.id)">回复</el-button>
<el-button type="text" style="color: red" @click="del(item.id)" v-if="user.id === item.uid" :disabled=item.isDelete>删除</el-button>
</div>
</div>
</div>
</div>
<div v-if="item.children.length" style="padding-left: 150px;">
<div v-for="subItem in item.children" :key="subItem.id" style="background-color: #f0f0f0; padding: 5px 20px">
<!-- 回复列表-->
<div style="font-size: 14px; padding: 5px 0; line-height: 25px">
<div>
<b style="color: #3a8ee6" v-if="subItem.pnickname">@{{ subItem.pnickname }}</b>
</div>
<div style="padding-left: 5px">
<b>{{ subItem.username }}:</b>
<span>{{ subItem.content }}</span>
</div>
<div style="display: flex; line-height: 20px; margin-top: 5px; padding-left: 5px">
<div style="width: 200px;">
<el-icon><Clock /></el-icon><span style="margin-left: 5px">{{ subItem.time }}</span>
</div>
<div style="text-align: right; flex: 1">
<el-button style="margin-left: 5px" type="text" @click="handleReply(subItem.id)">回复</el-button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
3.删除评论
<el-button type="text" style="color: red" @click="del(subItem.id)" v-if="user.id === subItem.uid">删除</el-button>
本人只能删除自己发布的评论,其他评论只有回复功能,通过v-if来限制;
如果已点击删除,为了保持原有的逻辑顺序,将显示[当前评论已经删除]的提示:
@ApiOperation("评论者删除当前评论,实则是把评论内容跟换为[当前评论已经删除],isDelete变为false并且无法再删除")
@PostMapping("/delete/{id}")
public Result delete(@PathVariable Integer id) {
Comment comment = commentService.getById(id);
comment.setIsDelete(false);
String content = "[当前评论已经删除]";
comment.setContent(content);
save(comment);
return Result.success();
}
数据库的is_delete字段将被修改为0,表明已经删除,然后再把”回复“和”删除“按钮隐藏:
<el-button style="margin-left: 5px" type="text" v-if="subItem.isDelete!=0" @click="handleReply(subItem.id)">回复</el-button>
<el-button type="text" style="color: red" @click="del(subItem.id)" v-if="user.id === subItem.uid && subItem.isDelete!=0">删除</el-button>
三、效果展示