评论系统与情感分析

张开发
2026/4/21 7:30:28 15 分钟阅读

分享文章

评论系统与情感分析
第4天-3评论系统与情感分析掘金标题 如何设计一个高互动的博客评论系统含情感分析CSDN标题Vue 3 LocalStorage 实现博客评论系统支持回复、点赞、情感分析前言评论区是博主与读者互动的重要场所。一个设计良好的评论系统可以增加读者参与感和粘性帮助博主了解读者需求形成良好的社区氛围今天分享如何实现一个功能完备的评论系统并加入情感分析功能功能设计功能列表评论系统功能 ├── 评论列表展示 │ ├── 按时间排序 │ ├── 回复嵌套显示 │ └── 分页加载 ├── 评论交互 │ ├── 发布评论 │ ├── 回复评论 │ ├── 点赞评论 │ └── 删除评论 └── 智能功能 ├── 评论字数统计 ├── 敏感词过滤 └── 情感分析核心实现1. 评论数据结构// src/types/comment.tsexportinterfaceComment{id:stringarticleId:stringuserId:stringuserName:stringuserAvatar:stringcontent:stringcreateTime:numberlikes:numberreplies:Comment[]sentiment?:positive|neutral|negative// 情感分析结果isLiked?:boolean}exportinterfaceCommentForm{content:stringreplyTo?:string}2. 评论服务// src/services/comment.tsimport{defineStore}frompiniaimport{ref,computed}fromvueimporttype{Comment,CommentForm}from/types/comment// 情感分析函数简化版functionanalyzeSentiment(text:string):positive|neutral|negative{constpositiveWords[赞,好,棒,厉害,感谢,有用,学习了,支持下,期待,喜欢]constnegativeWords[差,烂,垃圾,没用,失望,无语,问题,错误,bug]letscore0positiveWords.forEach(word{if(text.includes(word))score})negativeWords.forEach(word{if(text.includes(word))score--})if(score0)returnpositiveif(score0)returnnegativereturnneutral}exportconstuseCommentStoredefineStore(comment,(){constcommentsrefComment[]([])// 获取文章评论constgetCommentsByArticlecomputed((){return(articleId:string)comments.value.filter(cc.articleIdarticleId).sort((a,b)b.createTime-a.createTime)})// 加载评论functionloadComments(articleId:string){constkeycomments_${articleId}constdatalocalStorage.getItem(key)if(data){comments.valueJSON.parse(data)}}// 保存评论functionsaveComments(articleId:string){constkeycomments_${articleId}constarticleCommentscomments.value.filter(cc.articleIdarticleId)localStorage.setItem(key,JSON.stringify(articleComments))}// 添加评论functionaddComment(articleId:string,form:CommentForm,user:{id:string;name:string;avatar:string}){constcomment:Comment{id:comment_${Date.now()}_${Math.random().toString(36).slice(2)},articleId,userId:user.id,userName:user.name,userAvatar:user.avatar,content:form.content,createTime:Date.now(),likes:0,replies:[],sentiment:analyzeSentiment(form.content)}if(form.replyTo){// 添加回复constparentCommentfindComment(comments.value,form.replyTo)if(parentComment){parentComment.replies.push(comment)}}else{// 添加顶层评论comments.value.unshift(comment)}saveComments(articleId)returncomment}// 查找评论functionfindComment(list:Comment[],id:string):Comment|null{for(constitemoflist){if(item.idid)returnitemif(item.replies.length0){constfoundfindComment(item.replies,id)if(found)returnfound}}returnnull}// 点赞评论functiontoggleLike(commentId:string){constcommentfindComment(comments.value,commentId)if(comment){comment.isLiked!comment.isLiked comment.likescomment.isLiked?1:-1constarticleIdcomment.articleIdsaveComments(articleId)}}// 获取评论统计functiongetStats(articleId:string){constarticleCommentscomments.value.filter(cc.articleIdarticleId)constallComments[...articleComments]articleComments.forEach(c{allComments.push(...c.replies)})constsentiments{positive:allComments.filter(cc.sentimentpositive).length,neutral:allComments.filter(cc.sentimentneutral).length,negative:allComments.filter(cc.sentimentnegative).length}return{total:allComments.length,...sentiments}}return{comments,getCommentsByArticle,loadComments,addComment,toggleLike,getStats}})3. 评论组件!-- src/components/comment/CommentSection.vue -- template div classcomment-section h3 classsection-title 评论 ({{ totalComments }}) /h3 !-- 评论统计 -- div v-iftotalComments 0 classsentiment-stats span classstat positive 赞 {{ stats.positive }}/span span classstat neutral 中立 {{ stats.neutral }}/span span classstat negative 待改进 {{ stats.negative }}/span /div !-- 评论输入 -- div classcomment-input el-avatar :size40 src/avatar.png / div classinput-wrapper el-input v-modelcommentContent typetextarea :rows3 :placeholderreplyTo ? 回复 ${replyToName} : 写下你的评论... / div classinput-footer span classchar-count{{ commentContent.length }}/500/span el-button typeprimary :disabled!commentContent.trim() clicksubmitComment 发布评论 /el-button /div /div /div !-- 评论列表 -- div classcomment-list CommentItem v-forcomment in comments :keycomment.id :commentcomment replyhandleReply likehandleLike / /div !-- 加载更多 -- div v-ifhasMore classload-more el-button clickloadMore加载更多/el-button /div /div /template script setup langts import { ref, computed, onMounted } from vue import { useCommentStore } from /services/comment import { ElMessage } from element-plus import CommentItem from ./CommentItem.vue const props defineProps{ articleId: string }() const commentStore useCommentStore() const commentContent ref() const replyTo refstring() const replyToName ref() const page ref(1) const pageSize 10 const comments computed(() { return commentStore.getCommentsByArticle.value(props.articleId) .slice(0, page.value * pageSize) }) const totalComments computed(() { return comments.value.length }) const hasMore computed(() { return comments.value.length commentStore.getCommentsByArticle.value(props.articleId).length }) const stats computed(() { return commentStore.getStats(props.articleId) }) function handleReply({ id, userName }: { id: string; userName: string }) { replyTo.value id replyToName.value userName } function handleLike(id: string) { commentStore.toggleLike(id) } function submitComment() { if (commentContent.value.length 500) { ElMessage.warning(评论不能超过500字) return } // 模拟当前用户 const user { id: current_user, name: 访客, avatar: /avatar.png } commentStore.addComment(props.articleId, { content: commentContent.value, replyTo: replyTo.value || undefined }, user) commentContent.value replyTo.value replyToName.value ElMessage.success(评论发布成功) } function loadMore() { page.value } onMounted(() { commentStore.loadComments(props.articleId) }) /script style scoped .comment-section { margin-top: 40px; padding: 24px; background: #fff; border-radius: 12px; } .section-title { font-size: 20px; margin-bottom: 16px; } .sentiment-stats { display: flex; gap: 16px; margin-bottom: 20px; padding: 12px; background: #f5f7fa; border-radius: 8px; } .stat { font-size: 14px; } .positive { color: #67c23a; } .neutral { color: #909399; } .negative { color: #f56c6c; } .comment-input { display: flex; gap: 12px; margin-bottom: 24px; } .input-wrapper { flex: 1; } .input-footer { display: flex; justify-content: space-between; align-items: center; margin-top: 8px; } .char-count { font-size: 12px; color: #999; } .comment-list { display: flex; flex-direction: column; gap: 20px; } .load-more { text-align: center; margin-top: 20px; } /style!-- src/components/comment/CommentItem.vue -- template div classcomment-item :class{ is-reply: isReply } el-avatar :sizeisReply ? 32 : 40 :srccomment.userAvatar / div classcomment-content div classcomment-header span classuser-name{{ comment.userName }}/span span classsentiment-badge :classcomment.sentiment {{ sentimentText }} /span span classcreate-time{{ formatTime(comment.createTime) }}/span /div div classcomment-body{{ comment.content }}/div div classcomment-actions span classaction-btn click$emit(like, comment.id) {{ comment.isLiked ? ❤️ : }} {{ comment.likes }} /span span classaction-btn clickhandleReply 回复 /span /div !-- 回复列表 -- div v-ifcomment.replies?.length 0 classreplies CommentItem v-forreply in comment.replies :keyreply.id :commentreply :is-replytrue reply$emit(reply, $event) like$emit(like, reply.id) / /div /div /div /template script setup langts import { computed } from vue import type { Comment } from /types/comment const props defineProps{ comment: Comment isReply?: boolean }() defineEmits([reply, like]) const sentimentText computed(() { const map { positive: 好评, neutral: 中立, negative: 待改进 } return map[props.comment.sentiment || neutral] }) function formatTime(timestamp: number) { const date new Date(timestamp) const now new Date() const diff now.getTime() - date.getTime() if (diff 60000) return 刚刚 if (diff 3600000) return ${Math.floor(diff / 60000)}分钟前 if (diff 86400000) return ${Math.floor(diff / 3600000)}小时前 if (diff 604800000) return ${Math.floor(diff / 86400000)}天前 return date.toLocaleDateString() } function handleReply() { // 滚动到评论输入框 document.querySelector(.comment-input)?.scrollIntoView({ behavior: smooth }) } /script style scoped .comment-item { display: flex; gap: 12px; } .comment-item.is-reply { margin-top: 12px; } .comment-content { flex: 1; } .comment-header { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; } .user-name { font-weight: 600; color: #333; } .sentiment-badge { font-size: 12px; padding: 2px 8px; border-radius: 10px; } .sentiment-badge.positive { background: #e1f3d8; color: #67c23a; } .sentiment-badge.neutral { background: #f4f4f5; color: #909399; } .sentiment-badge.negative { background: #fef0f0; color: #f56c6c; } .create-time { font-size: 12px; color: #999; } .comment-body { line-height: 1.6; color: #333; } .comment-actions { display: flex; gap: 16px; margin-top: 8px; } .action-btn { font-size: 13px; color: #666; cursor: pointer; transition: color 0.2s; } .action-btn:hover { color: #409eff; } .replies { margin-top: 16px; padding-left: 16px; border-left: 2px solid #ebeef5; } /style效果展示评论系统上线后可以获得读者反馈数据通过情感分析了解文章质量社区活跃度提升读者互动意愿改进方向根据负面反馈优化内容进阶功能建议接入后端实现用户登录和评论管理添加评论审核功能防止垃圾评论实现提及功能通知被回复的用户相关资源在线演示[fineday.vip]

更多文章