评论区实现 前端Vue
根据后端部分定义评论区功能实现 golang后端部分-CSDN博客,重点需要实现三个部分,1.当前用户发起新根评论请求;2.评论区展示部分;3.某一根评论的子评论展示以及回复组件显示。
整体流程解释
数据从后端接收,整体在index文件中第一次进行存储,利用inject注入方式,将数据从父组件传递到子组件当中进行显示。对于每一个评论的获取,依赖评论数据中的评论id进行定位,进行后续的回复发送等等。
效果如下所示。
1.当前用户发起新根评论组件 组件名topCommentReply.vue
效果如下:
<template><div class="top-comment-input"><!-- 用户头像 --><img :src="userInfo.userAvatar" class="avatar" alt="用户头像" /><!-- 评论输入区域 --><div class="input-area"><textareav-model="commentContent"placeholder="说点什么..."rows="3"></textarea><div class="btn-wrapper"><button @click="submitComment" :disabled="isLoading" v-loading="isLoading">发布</button></div></div></div></template><script>import { ObjectId } from 'bson';export default {inject:["sendWSMessage", "userInfo", "videoId"],name: 'TopCommentReply',data() {return {commentContent: '',isLoading: false};},methods: {submitComment() {if (!this.commentContent.trim()) {this.$message.error('请输入评论内容');return;}this.isLoading = true;const replyComment = this.sendWSMessage;console.log('this.videoId', this.videoId);const comment = {"videoId": this.videoId,"curCommentId": new ObjectId().toString(),"userId": this.userInfo.userId,"userName": this.userInfo.userName,"userAvatar": this.userInfo.userAvatar,"content": this.commentContent,"commentType": 0,};replyComment(comment);this.$emit('post-submit-top-reply', comment);this.isLoading = false;}}};</script><style scoped>.top-comment-input {display: flex;gap: 12px;margin-bottom: 2em;}.avatar {width: 40px;height: 40px;border-radius: 50%;}.input-area {flex: 1;display: flex;flex-direction: column;gap: 10px;}.input-area textarea {width: 100%;padding: 10px;border-radius: 6px;border: 1px solid #ccc;resize: none;font-size: 14px;outline: none;}.btn-wrapper {display: flex;justify-content: flex-end;}.btn-wrapper button {padding: 8px 20px;background-color: #0f1014;color: #fff;border: none;border-radius: 4px;cursor: pointer;}.btn-wrapper button:hover {background-color: #2d2d2d;}.btn-wrapper button:disabled {opacity: 0.6;cursor: not-allowed;}</style>
2. 整体评论区部分分为两个组件commentSection.Vue和commentReplyItem.vue
2.1commentSection.Vue
<template><div class="firstglobals"><!-- 头像 --><div class="avatar"><img :src="data.userAvatar" style="width: 56px; height: 56px; border-radius: 50%;" alt="" /></div><!-- 内容 --><div class="content"><div class="usertop"><div style="display: flex;gap: 10px;"><div class="username">{{ data.userName }}</div><div class="tags" v-if="data.tag === 1">作者</div></div><div class="time">{{ formatTime(data.createTime) }}</div></div><div style="display: flex; flex-direction: column; margin-top: 1em;"><div class="text">{{ data.content }}</div><div style="display: flex; align-self: flex-end;"><img src="@/assets/images/点赞.png" style="width: 20px;" alt="" /></div><div class="but" @click="toggleReplyBox(data.curCommentId)">回复</div></div><div v-if="isReplyBoxVisible" class="reply-box"><textarea v-model="replyContent" placeholder="输入你的回复..." rows="3"></textarea><button @click="submitReply(data.curCommentId)" v-loading='isLoading'>发布</button></div><!-- 回复组件 --><div><div v-if = "replyComments != null"><div v-for="(item, index) in replyComments" :key="index"><CommentReplyItem :dataCode="dataCode" :replyData="item"@post-submit-reply="handleSubmitReply" /></div></div><div class="reply-buttons"><div v-show="!showAllReplies" class="load-more" @click="showReplies">加载更多回复 </div><div v-show="isSomeRepliesLoaded" class="load-more" @click="hideReplies">收起回复</div></div></div></div></div></template><script>import CommentReplyItem from '@/views/video/components/commentReplyItem.vue';import { getComment, } from '@/apis/comment/comment.js';import { ObjectId } from 'bson';export default {name: 'CommentSection',components: {CommentReplyItem},props: {data: {type: Object,required: true,validator(value) {return ['userImg', 'userName', 'time', 'content','ReplyData', 'id', 'tag'].every(prop => prop in value);}},dataCode: {type: Number,default: null}},data() {return {replyContent: '',isLoading: false,showAllReplies: false,isSomeRepliesLoaded: false,isAllRepliesLoaded: false,replyComments: [],curPage: 1,totalPage: 10,};},computed: {isReplyBoxVisible() {return this.activeReplyId === this.data.curCommentId;},},inject: ['activeReplyId', 'setActiveReplyId', `sendWSMessage`, `userInfo`, `videoId`],methods: {formatTime(ts) {if (!ts) return '';const date = new Date(ts * 1000); return date.toLocaleString(); },handleSubmitReply(comment) {this.replyComments.push(comment);this.$emit('post-submit-reply', comment);},toggleReplyBox(id) {console.log('toggleReplyBox called with id:', id);console.log('this.activeReplyId1:', this.activeReplyId);if (this.setActiveReplyId) {this.setActiveReplyId(this.isReplyBoxVisible ? null : id);console.log('this.activeReplyId2:', this.activeReplyId);}},submitReply(id) {if (this.replyContent.trim()) {console.log('提交的回复内容:', this.replyContent);this.isLoading = true;const replyComment = this.sendWSMessage;console.log('this.videoId', this.videoId);const comment = {"videoId": this.videoId,"rootCommentId": id,"parentId": id,"parentUserId": this.data.userId,"parentUserName": this.data.userName,"curCommentId": new ObjectId().toString(),"userId": this.userInfo.userId,"userName": this.userInfo.userName,"userAvatar": this.userInfo.userAvatar,"content": this.replyContent,"commentType": 1,};replyComment(comment);this.replyComments.push(comment);this.isLoading = false;this.replyContent = '';this.setActiveReplyId(null);} else {this.$message.error('请输入回复内容');this.isLoading = false;}},async showReplies() {this.isSomeRepliesLoaded = true;const jsonData = {rootCommentId: this.data.curCommentId,commentType: 1,page: this.curPage,};try {this.curPage += 1;const [error, data] = await getComment(this.videoId, jsonData);if (error) throw error;if (data != null) {this.replyComments.push(...data.comments);console.log('获取评论成功:', data.comments);}} catch (err) {console.error('获取评论失败:', err);}},hideReplies() {this.isSomeRepliesLoaded = false;this.showAllReplies = false;this.curPage = 1;this.replyComments = [];},},mounted() {console.log("头像", this.data.userImg)console.log("评论数据", this.data);}};</script><style scoped>/* 样式部分保持不变 */.but {width: 60px;padding: 5px 0px;background: #f1f1f1;border-radius: 4px;display: flex;justify-content: center;align-content: center;font-weight: 400;font-size: 14px;color: #0f1014;text-align: left;font-style: normal;text-transform: none;}.tags {width: 32px;height: 18px;background: #0F1014;border-radius: 4px;color: #FFFFFF;font-weight: 400;font-size: 10px;line-height: 12px;text-align: center;display: flex;justify-content: center;align-items: center;}.but:hover {background: #ebe4e4;}.text {font-weight: 400;font-size: 18px;color: #000000;line-height: 21px;text-align: left;font-style: normal;text-transform: none;}.time {font-weight: 400;font-size: 12px;color: #666666;line-height: 14px;text-align: left;font-style: normal;text-transform: none;}.avatar {width: 56px;height: 56px;border-radius: 30px;}.usertop {display: flex;flex-direction: column;gap: 5px;}.username {font-weight: 700;font-size: 16px;color: #0f1014;line-height: 19px;text-align: left;font-style: normal;text-transform: none;}.content {display: flex;flex-direction: column;margin-left: 1em;margin-top: 10px;flex: 1;}.firstglobals {display: flex;justify-content: start;margin-top: 2em;}.reply-buttons {display: flex;gap: 10px; /* 两个按钮之间的间距 */
}.load-more {display: inline-flex; /* 让它变成“内联元素 + 可用 flex” */align-items: center;margin-top: 30px;color: #0066cc;cursor: pointer;font-size: 14px;
}.load-more:hover {text-decoration: underline;}.reply-box {margin-top: 10px;display: flex;flex-direction: column;gap: 10px;align-items: end;position: relative;width: 98%;align-self: flex-end;}.reply-box textarea {width: 100%;padding: 10px;border-radius: 4px;border: 1px solid #ddd;resize: none;outline: none;}.reply-box button {align-self: flex-end;padding: 10px 20px;border-radius: 4px;border: none;background-color: #070707;color: white;cursor: pointer;}.reply-box button:hover {background-color: #2d2d2d;}</style>
2.2commentReplyItem.vue
<template><div class="reply-comments"><div class="top-user"><div style="display: flex; justify-content: center; align-content: center; gap: 8px;"><img :src="replyData.userAvatar" style="width: 24px; height: 24px; border-radius: 50%;" alt=""><span class="username">{{ replyData.userName }}</span></div><div class="tags" v-if="replyData.anthTags === 1 || replyData.anthTags === 3">作者</div><div class="hf">回复</div><div style="display: flex; justify-content: center; align-content: center; gap: 8px;"><!-- <img :src="replyData.userImg2" style="width: 24px; height: 24px; border-radius: 50%;" alt=""> --><span class="username">{{ replyData.parentUserName }}</span></div><div class="tags" v-if="replyData.anthTags === 2 || replyData.anthTags === 3">作者</div><div class="time">{{ formatTime(replyData.createTime) }}</div></div><div class="content">{{ replyData.content }}</div><div style="display: flex; align-self: flex-end;"><img src="@/assets/images/点赞.png" style="width: 20px;" alt=""></div><div class="but" @click="toggleReplyBox()">回复</div><div v-if="isReplyBoxVisible" class="reply-box"><textarea v-model="replyContent" placeholder="输入你的回复..." rows="3"></textarea><button @click="submitReply(replyData.rootCommentId)" v-loading="isLoading">发布</button></div></div>
</template><script>import { ObjectId } from 'bson';
export default {name: 'CommentReplyItem',props: {replyData: {type: Object,required: true,validator(value) {return ['userImg1', 'userName1', 'userImg2', 'userName2','replytime', 'replycontent', 'anthTags', 'id'].every(prop => prop in value);}},dataCode: {type: Number,default: null}},data() {return {replyContent: '',isLoading: false};},computed: {isReplyBoxVisible() {return this.activeReplyId === this.replyData.curCommentId;}},inject: ['activeReplyId', 'setActiveReplyId', 'sendWSMessage', 'userInfo', 'videoId'],methods: {formatTime(ts) {if (!ts) return '';const date = new Date(ts * 1000); return date.toLocaleString(); },toggleReplyBox() {console.log('toggleReplyBox');if (this.setActiveReplyId) {this.setActiveReplyId(this.isReplyBoxVisible ? null : this.replyData.curCommentId);}},submitReply(id) {if (this.replyContent.trim()) {const replyComment = this.sendWSMessage;console.log('提交的回复内容:', this.replyContent);this.isLoading = true;console.log('this.videoId', this.videoId);const comment = {"videoId": this.videoId,"rootCommentId": id,"parentId": this.replyData.curCommentId,"parentUserId": this.replyData.userId,"parentUserName": this.replyData.userName,"curCommentId": new ObjectId().toString(),"userId": this.userInfo.userId,"userName": this.userInfo.userName,"userAvatar": this.userInfo.userAvatar,"content": this.replyContent,"commentType": 1,};replyComment(comment)this.$emit('post-submit-reply', comment);this.isLoading = false;this.replyContent = '';this.setActiveReplyId(null);} else {this.$message.error('请输入回复内容');}}},watch: {replyData: {handler(newValue) {console.log('newValue', newValue.anthTags);},deep: true}},mounted() {console.log("newValue", this.replyData.anthTags);}
};
</script><style scoped>
/* 样式部分保持不变 */
.but {width: 60px;padding: 5px 0px;background: #F1F1F1;border-radius: 4px;display: flex;justify-content: center;align-content: center;font-weight: 400;font-size: 14px;color: #0F1014;margin-left: 32px;cursor: pointer;
}.but:hover {background: #ebe4e4;
}.content {font-weight: 400;font-size: 18px;color: #000000;line-height: 21px;text-align: left;margin-left: 32px;margin-top: 10px;
}.time {font-weight: 400;font-size: 12px;color: #666666;line-height: 14px;text-align: left;
}.hf {font-weight: 400;font-size: 14px;color: #B9B9B9;line-height: 16px;text-align: left;
}.tags {width: 32px;height: 18px;background: #0F1014;border-radius: 4px;color: #FFFFFF;font-weight: 400;font-size: 10px;line-height: 12px;text-align: center;display: flex;justify-content: center;align-items: center;
}.username {height: 24px;font-weight: 500;font-size: 13px;color: #0F1014;line-height: 15px;display: flex;justify-content: center;align-items: center;
}.top-user {display: flex;align-items: center;gap: 8px;
}.reply-comments {display: flex;flex-direction: column;margin-top: 1em;
}.reply-box {margin-top: 10px;display: flex;flex-direction: column;gap: 10px;align-items: end;position: relative;width: 95%;align-self: flex-end;
}.reply-box textarea {width: 100%;padding: 10px;border-radius: 4px;border: 1px solid #ddd;resize: none;outline: none;
}.reply-box button {align-self: flex-end;padding: 10px 20px;border-radius: 4px;border: none;background-color: #070707;color: white;cursor: pointer;
}.reply-box button:hover {background-color: #2d2d2d;
}
</style>
3.index.Vue文件
<template><div class="video-page-container"><!-- 视频播放区 --><div class="video-player-wrapper"><easy-player:key="videoUrl"ref="videoplay":video-url="videoUrl":show-progress="true"format="hls"class="video-player"@error="restartPlayer"/></div><!-- 评论发布区 --><div class="top-comment"><TopCommentReply @post-submit-top-reply="recvTopHandler" /></div><!-- 评论列表区 --><div class="comments-section"><divv-for="comment in commentList":key="comment.id"class="comment-wrapper"><CommentSection :data="comment" /></div></div></div>
</template><script>
import { computed, ref } from 'vue';
import CommentSection from './components/commentSection.vue';
import TopCommentReply from './components/topCommentReply.vue';
import { getComment } from '@/apis/comment/comment.js';
import { ElMessage } from 'element-plus';export default {name: "VideoPlayer",components: {CommentSection,TopCommentReply},inject:["userInfo", "ws"],data() {return {videoId: this.$route.params.videoId,videoUrl: this.$route.query.videoUrl,userId: 0,userImg: "",// userInfo: {},activeReplyId: ref(null),commentList: [],};},created() {this.fetchComments();// this.initWebSocket();},// mounted() {// this.initWebSocket();// },provide() {return {sendWSMessage: this.sendWSMessage,setActiveReplyId: this.setActiveReplyId,activeReplyId: computed(() => this.activeReplyId),// userInfo: computed(() => this.userInfo),videoId: computed(() => this.videoId),};},// beforeUnmount() {// if (this.ws) {// this.ws.close();// }// },methods: {async fetchComments() {const jsonData = {rootCommentId: "-1",commentType: 0,page: 1,};try {const [error, data] = await getComment(this.videoId, jsonData);if (error) throw error;this.commentList = data.comments;} catch (err) {console.error('获取评论失败:', err);}},// initWebSocket() {// const Url = "ws://192.168.229.130:8080/video/ws/comment?userId=";// this.userId = sessionStorage.getItem('userId')// const wsUrl = Url + this.userId;// console.log("wsUrl", wsUrl);// // console.log("ws userInfo", this.userInfo);// // this.userInfo = {// // userId: this.userId,// // userAvatar: "http://localhost:8888/video/static/covers/57739617071403008.png",// // userName: "JohnDoe",// // };// this.ws = new WebSocket(wsUrl);// this.ws.onopen = () => {// console.log("WebSocket连接成功");// };// this.ws.onmessage = (event) => {// const msg = JSON.parse(event.data);// console.log("WebSocket消息:", msg);// };// this.ws.onerror = (error) => {// console.error("WebSocket错误:", error);// };// this.ws.onclose = () => {// console.log("WebSocket连接关闭");// };// },recvTopHandler(comment) {this.commentList.push(comment);},sendWSMessage(comment) {if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {console.error('WebSocket未连接');return false;}try {const jsonStr = JSON.stringify(comment);this.ws.send(jsonStr);ElMessage.success('消息已发送');return true;} catch (error) {ElMessage.error('消息发送失败');console.error('消息发送失败:', error);return false;}},setActiveReplyId(id) {this.activeReplyId = id;},restartPlayer() {console.log("播放器出错,尝试重新加载...");},},
};
</script><style scoped>
.video-page-container {display: flex;flex-direction: column;align-items: center;width: 100%;
}/* 视频播放器区域 */
.video-player-wrapper {width: 100%;max-width: 1200px;background: #000;aspect-ratio: 16/9; /* 保持16:9比例 */margin-bottom: 20px;
}.video-player {width: 100%;height: 100%;object-fit: contain;
}/* 发布评论输入框 */
.top-comment {width: 100%;max-width: 1200px;padding: 10px;background: #fff;margin-bottom: 10px;
}/* 评论区列表 */
.comments-section {width: 100%;max-width: 1200px;background: #fff;padding: 10px;box-sizing: border-box;
}.comment-wrapper {border-bottom: 1px solid #eee;padding: 10px 0;
}
</style>