有需要的小伙伴直接拿代码即可,不需要下载依赖,目前是初始版本,后期会进行代码的优化。
评论组件如下:
创建 comment.vue 文件。
表情组件 VueEmoji.vue 在评论组件中使用。
<template><div class="comment"><div class="flex_box"><h2>评论 3508</h2><p>文明上网理性发言</p></div><div class="comment-header"><div class="header_children"><el-tooltip class="item" effect="dark" content="点我更换头像" placement="top-start"><div @click="handleClick"><input type="file" style="display: none" @change="dealWithdAvatar" ref="avatar" /><el-avatar:src="avatarUrl? avatarUrl: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'":size="40"></el-avatar></div></el-tooltip><el-input:placeholder="placeholderText"v-model="context"class="input"type="textarea"resize="none"size="mini"clearable:maxlength="contentLength"@focus="isShowSecReply(undefined)"></el-input></div><div class="header_btn"><!-- 表情 --><vue-emoji @chooseEmoji="chooseEmoji" :keyId="'context'"></vue-emoji><el-buttontype="primary"style="height: 40px"@click="addComment(articleId, undefined)">{{ buttonText }}</el-button></div></div><div class="comment-body" v-for="(item, index) in comments" :key="item._id + '' + index"><!-- 一级评论 --><div class="first-comment" v-if="index < morelist.index"><el-avatar :size="40" :src="item.avatarUrl"></el-avatar><div class="content"><!-- 一级评论用户昵称 --><h3>{{ item.username }}</h3><!-- 一级评论发布时间 --><span>{{ item.date }}</span><!-- 一级评论评论内容 --><p>{{ item.content }}</p><!-- 一级评论评论点赞 --><div class="comment-right"><!-- <iclass="el-icon-trophy"@click="giveALike(item, item._id)":class="item.favour.includes(userId) ? 'active' : ''"></i>{{ item.favour.length || 0 }} --><iclass="el-icon-chat-dot-round"@click="isShowSecReply(item._id)">回复</i><iclass="el-icon-delete"@click="deleteComment(item._id, undefined)"v-if="userId === item.userId">删除</i></div><!-- 回复一级评论 --><div class="reply-comment" v-show="isShowSec === item._id"><el-input:placeholder="placeholderText"class="input"v-model.trim="replyContext":maxlength="contentLength"clearable></el-input><div class="flex_one_box"><!-- 表情 --><vue-emoji @chooseEmoji="chooseEmoji" :keyId="item._id" :layer="comments"></vue-emoji><el-buttontype="primary"size="mini"class="reply-button"@click="addComment(item._id, item.username)">回复</el-button></div></div><!-- 次级查看更多 --><div class="li_top" @click="changeChildrenMore" v-if="item.replyInfo?.length > childrenMorelist.clickIndex"><span style="color: rgb(21 66 231);">共100条评论</span><i class="el-icon-caret-bottom" v-show="!childrenMorelist.value"></i> <i class="el-icon-caret-top" v-show="childrenMorelist.value"></i></div><!-- 次级评论 --><ul v-infinite-scroll="load(item.replyInfo)" infinite-scroll-delay="200" style="overflow:auto" class="infinite_list"> <!-- === --><li class="second-comment" v-for="(reply, index) in item.replyInfo" :key="reply._id + '' + index"><!-- 次级评论头像,该用户没有头像则显示默认头像 --><template v-if="index < childrenMorelist.index"><el-avatar :size="40" :src="reply.avatarUrl"></el-avatar><div class="content"><!-- 次级评论用户昵称 --><h3>{{ reply.username }}</h3><!-- 次级评论评论时间 --><span>{{ reply.date }}</span><span class="to_reply">{{ reply.username }}</span>回复<span class="to_reply">{{ reply.replyName }}</span>:<p>{{ reply.content }}</p><!-- 次级评论评论点赞 --><div class="comment-right"><!-- <iclass="el-icon-trophy"@click="giveALike(reply, item._id)":class="reply.favour.includes(userId) ? 'active' : ''"></i>{{ reply.favour ? reply.favour.length : 0 }} --><iclass="el-icon-chat-dot-round"@click="isShowSecReply(reply._id)">回复</i><iclass="el-icon-delete"@click="deleteComment(item._id, reply._id)"v-if="userId === reply.userId">删除</i></div><div class="reply-comment" v-show="isShowSec === reply._id"><el-input:placeholder="placeholderText"class="input"v-model.trim="replyContext":maxlength="contentLength"clearable></el-input><div class="flex_one_box"><!-- 表情 --><vue-emoji @chooseEmoji="chooseEmoji" :keyId="reply._id" :layer="item.replyInfo"></vue-emoji><el-buttontype="primary"size="mini"class="reply-button"@click="addComment(item._id, reply.username)">回复</el-button></div></div></div></template></li></ul></div></div></div><!-- 一级查看更多 --><el-button type="info" class="moreBtn" @click="changeMore" v-show="comments?.length > morelist.clickIndex">查看更多评论<i class="el-icon-caret-bottom" v-show="!morelist.value"></i> <i class="el-icon-caret-top" v-show="morelist.value"></i></el-button><!-- 暂无评论的空状态 --><el-empty :description="emptyText" v-show="comments.length === 0"></el-empty></div>
</template>
<script>
export default {props: {articleId: {//评论所属文章 idtype: String},emptyText: {// 评论为空的时候显示的文字type: String,default: "期待你的评论!"},buttonText: {// 按钮文字type: String,default: "评论"},contentLength: {// 评论长度type: Number,default: 150},placeholderText: {// 默认显示文字type: String,default: "请输入最多150字的评论..."}},data() {return {comments: [{_id: "first0", // 评论iddate: "2022.09.01", //创建日期username: "孤城浪人", //评论人userId: "1",avatarUrl:"https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png", //头像地址favour: ["1", "2", "3"], //点赞的用户idcontent: "666", //评论内容replyInfo: [//回复的内容{_id: "sec0", // 当前此条回复的iddate: "2022.09.01", //创建日期replyName: "孤城浪人", //回复的对象username: "孤城浪人", //评论人userId: "1",favour: ["2", "3", "4"],avatarUrl:"https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",content: "博主厉害了" //回复的内容}]},], // 获取得到的评论context: "", // 评论内容replyContext: "", //一级评论回复isShowSec: "", //是否显示次级回复框isClickId: "", //记录点击回复的评论iduserId: "1", // 浏览器指纹username: "孤城浪人", //你的用户名firstIdx: 1,secIdx: 1,avatarUrl:"https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",morelist: {index: '2',value: false,clickIndex: '2',},childrenMorelist: {index: '2',value: false,clickIndex: '2',},};},created() {// 获取评论数据// this.getCommentList();},methods: {chooseEmoji(keyId,layer,val) {if(layer) {this.replyContext += val;return;}this.context += val;},changeMore() {this.morelist.value = !this.morelist.value;if(this.morelist.value) {this.morelist.index = '99999999';}else {this.morelist.index = '2';}},changeChildrenMore() {this.childrenMorelist.value = !this.childrenMorelist.value;if(this.childrenMorelist.value) {this.childrenMorelist.index = '99999999';}else {this.childrenMorelist.index = '2';}},load(list) {list += 2},// 唤起文件选择handleClick() {this.$refs.avatar.click();},dealWithdAvatar(e) {const maxSize = 2 * 1024 * 1024;const file = Array.prototype.slice.call(e.target.files)[0];console.log(file);},// 获取本篇文章所有评论async getCommentList() {try {this.comments = [];let id = "";if (this.articleId == "messageBoard") {id = "messageBoard";} else {id = this.articleId;}// 获取某篇文章下的所有评论const res = await this.$api.getCommentsOfArticle({ id });this.comments = res.data.comments; //评论列表this.username = res.data.user?.username;this.avatarUrl = res.data.user?.avatarUrl;} catch (err) {this.$message.error(err);}},// 评论点赞giveALike(item, _id) {try {// 不允许同一个人重复点赞if (item.favour?.includes(this.userId)) {this.$message.info("您已经点过赞啦!");return;}//判断是给一级评论点赞还是二级评论,只有二级评论会有replyNameif (item.replyName) {// 给二级评论点赞,向后台提交数据} else {// 一级评论点赞,向后台提交数据}item.favour.push(this.userId);} catch (err) {this.$message.error(err);}},isShowSecReply(id) {console.log("一级input获取焦点");if (id) {this.isShowSec = id;if (this.isClickId === this.isShowSec) {this.isShowSec = "";} else {this.isShowSec = id;}this.isClickId = this.isShowSec;} else {this.isShowSec = this.isClickId = "";}},deleteComment(_id, replyId) {if (replyId) {// 删除二级评论,提交请求到后端// 成功后从本地记录中删除该评论const temp = this.comments.find(item => item._id == _id).replyInfo;for (let i = 0; i < temp.length; i++) {if (temp[i]._id == replyId) {temp.splice(i, 1);break;}}} else {// 删除一级评论,提交请求到后端// 成功后从本地记录中删除该评论for (let i = 0; i < this.comments.length; i++) {if (this.comments[i]._id == _id) {this.comments.splice(i, 1);}}}},async addComment(id, replyName) {let res = {};// 评论添加成功,返回的数据//本地更新评论列表if (replyName) {// 添加二级评论if (!this.replyContext) {this.$message.warning("评论或留言不能为空哦!");return;}// 模拟数据提交成功后返回数据res.data = {username: this.username,userId: this.userId,avatarUrl: this.avatarUrl,_id: "sec" + this.secIdx++, // 评论idreplyName,date: "2022.09.01", //创建日期favour: [], //点赞的用户idcontent: this.replyContext //评论内容};const comment = this.comments.find(item => item._id == id);if (!comment.replyInfo) {comment.replyInfo = [];}comment.replyInfo.push(res.data);this.replyContext = "";} else {// 添加一级评论,提交数据到后端if (!this.context) {this.$message.warning("评论或留言不能为空哦!");return;}// 模拟数据提交成功后返回数据res.data = {username: this.username,avatarUrl: this.avatarUrl,userId: this.userId,_id: "first" + this.firstIdx++, // 评论iddate: "2022.09.01", //创建日期articleId: this.articleId, // 评论的文章idfavour: [], //点赞的用户idcontent: this.context //评论内容};this.comments.push(res.data);this.context = "";}this.isShowSec = this.isClickId = "";console.log("this.comments",this.comments);}}
};
</script><style lang="scss" scoped>
.comment {min-height: 26vh;border-radius: 5px;margin-top: 2px;overflow: hidden;h3 {margin: 5px 0;}p {margin: 3px 0;}ul {list-style-type: none;}.flex_box {display: flex;align-items: center;margin-bottom: 30px;h2 {margin: 0;}p {font-size: 16px;color: #666;margin: 0 0 0 20px;}}.active {color: rgb(202, 4, 4);}.comment-header {position: relative;// height: 50px;padding: 10px 5px;// display: flex;// align-items: center;.header_children {display: flex;align-items: center;}.header_btn {display: flex;align-items: center;justify-content: space-between;padding: 0 20px 0 51px;margin-top: 10px;}.input {margin-left: 10px;margin-right: 20px;flex: 1;font-size: 14px;::v-deep .el-input__inner:focus {border-color: #dcdfe6;}}}.comment-body {font-size: 14px;.first-comment {display: flex;padding: 10px 20px;.input {::v-deep.el-input__inner:focus {border-color: #dcdfe6;}}i {margin-right: 5px;margin-left: 1vw;cursor: pointer;&:nth-child(3) {color: rgb(202, 4, 4);}}.content {margin-left: 10px;position: relative;flex: 1;& > span {font-size: 12px;color: rgb(130, 129, 129);}.comment-right {position: absolute;right: 0;top: 0;}.reply-comment {// height: 60px;// display: flex;// align-items: center;.flex_one_box {display: flex;justify-content: space-between;align-items: center;margin-top: 10px;}.reply-button {margin-left: 20px;height: 35px;}}.li_top {width: 200px;cursor: pointer;padding-left: 50px;}.infinite_list {max-height: 333px;}.second-comment {display: flex;padding: 10px 0 10px 5px;border-radius: 20px;background: #ffffff;.to_reply {color: rgb(126, 127, 128);}}}}}.moreBtn {width: 100%;i {font-size: 16px;}}::-webkit-scrollbar{width: 5px;height: 5px;background-color: #F5F5F5;}/*定义滚动条轨道 内阴影+圆角*/::-webkit-scrollbar-track{-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);border-radius: 10px;background-color: #F5F5F5;}/*定义滑块 内阴影+圆角*/::-webkit-scrollbar-thumb{border-radius: 10px;-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);background-color: #555;}
}
</style>
表情组件如下:
1. 创建 VueEmoji.vue 文件。
<template><div class="emoji"><ul class="emoji-default" v-show="isShowEmoji"><li v-for="(item, index) in emojiJson" :key="index"@click.stop="chooseEmojiDefault(item)">{{item}}</li></ul><div class="emoji-tabs"><div :class="!isShowEmoji ? 'emoji-tab' : 'new_tab'" @click="isShowEmoji = !isShowEmoji">{{ isShowEmoji ? '收起' : emojiJson[4]}}</div></div></div>
</template><script>const emojiJson = require("../utils/emoji.json");export default {props: {keyId: {type: String,required: false},layer: {type: Array || Object,required: false}},data() {return {emojiJson: emojiJson.data.split(','),isShowEmoji: false,}},methods: {chooseEmojiDefault(item) {console.log("item",item);this.$emit("chooseEmoji",this.keyId,this.layer,item);this.isShowEmoji = false;}}
}</script><style lang="scss" scoped>
// 纵向滚动条
@mixin scroll-bar($width: 10px) {&::-webkit-scrollbar-track {border-radius: 10px;background-color: #ffffff;}&::-webkit-scrollbar {width: $width;height: 10px;background-color: #ffffff;}&::-webkit-scrollbar-thumb {border-radius: 10px;background-color: rgba(0, 0, 0, 0.2);}
}.emoji {text-align: left;// width: 100%;// height: 100%;background: #fff;// border: 1px solid #dcdfe6;box-shadow: 0 2px 4px 0 rgb(0 0 0 / 12%), 0 0 6px 0 rgb(0 0 0 / 4%);.emoji-tabs {// border-top: 1px solid #DCDFE6;background: #f8f8f8;.emoji-tab {cursor: pointer;background: #ffffff;/* height: 100%; *//* padding: 5px 5px; *//* overflow: hidden; */text-align: center;/* line-height: 15px; */font-size: 25px}.new_tab {cursor: pointer;font-size: 14px;color: #1c33e5;text-align: center;padding: 5px 0;}}.emoji-default {width: calc(100% - 40px);height: 202px;overflow-y: auto;@include scroll-bar();padding: 0px 20px;li {display: inline-block;padding: 5px;font-size: 24px;width: 29px;height: 29px;overflow: hidden;cursor: pointer;}li:hover {background-color: #d5d5d5;}}
}</style>
2. 在写公共方法的地方创建 emoji.json 文件,里面是表情的数据,内容如下:
{"data": "😀,😁,😂,😃,😄,😅,😆,😉,😊,😋,😎,😍,😘,😗,😙,😚,😇,😐,😑,😶,😏,😣,😥,😮,😯,😪,😫,😴,😌,😛,😜,😝,😒,😓,😔,😕,😲,😷,😖,😞,😟,😤,😢,😭,😦,😧,😨,😬,😰,😱,😳,😵,😡,😠,💘,❤,💓,💔,💕,💖,💗,💙,💚,💛,💜,💝,💞,💟,❣,💪,👈,👉,☝,👆,👇,✌,✋,👌,👍,👎,✊,👊,👋,👏,👐,✍,🍇,🍈,🍉,🍊,🍋,🍌,🍍,🍎,🍏,🍐,🍑,🍒,🍓,🍅,🍆,🌽,🍄,🌰,🍞,🍖,🍗,🍔,🍟,🍕,🍳,🍲,🍱,🍘,🍙,🍚,🍛,🍜,🍝,🍠,🍢,🍣,🍤,🍥,🍡,🍦,🍧,🍨,🍩,🍪,🎂,🍰,🍫,🍬,🍭,🍮,🍯,🍼,☕,🍵,🍶,🍷,🍸,🍹,🍺,🍻,🍴,🌹,🍀,🍎,💰,📱,🌙,🍁,🍂,🍃,🌷,💎,🔪,🔫,🏀,⚽,⚡,👄,👍,🔥,🙈,🙉,🙊,🐵,🐒,🐶,🐕,🐩,🐺,🐱,😺,😸,😹,😻,😼,😽,🙀,😿,😾,🐈,🐯,🐅,🐆,🐴,🐎,🐮,🐂,🐃,🐄,🐷,🐖,🐗,🐽,🐏,🐑,🐐,🐪,🐫,🐘,🐭,🐁,🐀,🐹,🐰,🐇,🐻,🐨,🐼,🐾,🐔,🐓,🐣,🐤,🐥,🐦,🐧,🐸,🐊,🐢,🐍,🐲,🐉,🐳,🐋,🐬,🐟,🐠,🐡,🐙,🐚,🐌,🐛,🐜,🐝,🐞,🦋,😈,👿,👹,👺,💀,☠,👻,👽,👾,💣"
}
在 Vue 文件中使用,如下:
<template><div><comment :buttonText="'发表评论'"/></div>
</template>