Vue2+Element 封装评论+表情功能

2024-05-28 05:36

本文主要是介绍Vue2+Element 封装评论+表情功能,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

有需要的小伙伴直接拿代码即可,不需要下载依赖,目前是初始版本,后期会进行代码的优化。

评论组件如下:

创建 comment.vue 文件。

表情组件 VueEmoji.vue 在评论组件中使用。

<template><div class="comment"><div class="flex_box"><h2>评论 {{total}}</h2><p>文明上网理性发言</p></div><div class="comment-header"><div class="header_children"><i class="el-icon-user-solid img_width"></i><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"></vue-emoji><el-buttontype="primary"style="height: 40px"@click="addComment()"审核>{{ buttonText }}</el-button></div></div><div v-loading="bigLoading"><div class="comment-body" v-for="(item, index) in comments" :key="item.id + '' + index"><!-- 一级评论 --><div class="first-comment"><i class="el-icon-user-solid img_width"></i><div class="content"><!-- 一级评论用户昵称 --><div style="display: flex;align-items: center;"><h3>{{ item.memberName }}</h3><span v-if="item.auditStatus == '0'" style="color: #ddab16;margin-left: 10px">(待审核)</span></div><!-- 一级评论发布时间 --><span>{{ item.createTime }}</span><!-- 一级评论评论内容 --><p>{{ item.commentContent }}</p><!-- 一级评论评论点赞 --><div class="comment-right"><iclass="el-icon-chat-dot-round"@click="isShowSecReply(item)">回复</i><iv-if="userInfor.memberName == item.memberName"class="el-icon-delete"@click="deleteComment(item, undefined)">删除</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" :layer="comments"></vue-emoji><el-buttontype="primary"size="mini"class="reply-button"@click="addComment(item)">回复</el-button></div></div><!-- 次级查看更多 --><div class="li_top" v-if="item.commentReplyInfoList?.length > 0" @click="hanlePublicTotal(item)"><span style="color: rgb(21 66 231);">共{{item.commentReplyCount}}条评论</span><i class="el-icon-caret-bottom" v-show="item.publicTotal"></i><i class="el-icon-caret-top" v-show="!item.publicTotal"></i></div><!-- 次级评论 --><ul v-infinite-scroll="load(item.commentReplyInfoList)" infinite-scroll-delay="200" style="overflow:auto" class="infinite_list" v-if="item.publicTotal"> <li v-for="(reply, index) in item.commentReplyInfoList" :key="reply.id + '' + index"><!-- 次级评论头像,该用户没有头像则显示默认头像 --><template><div class="second-comment"><i class="el-icon-user-solid img_width"></i><div class="content"><!-- 次级评论用户昵称 --><div style="display: flex;align-items: center;"><h3>{{ reply.memberName }}</h3><span v-if="reply.auditStatus == '0'" style="color: #ddab16;margin-left: 10px">(待审核)</span></div><!-- 次级评论评论时间 --><span>{{ reply.createTime }}</span><span class="to_reply">{{ reply.memberName }}</span>回复<span class="to_reply">{{ reply.replyMemberName }}</span>:<p>{{ reply.commentContent }}</p><!-- 次级评论评论点赞 --><div class="comment-right"><iclass="el-icon-chat-dot-round"@click="isShowSecReply(reply)">回复</i><iv-if="userInfor.memberName == reply.memberName"class="el-icon-delete"@click="deleteComment(item, reply)">删除</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" :layer="item.commentReplyInfoList"></vue-emoji><el-buttontype="primary"size="mini"class="reply-button"@click="addComment(item,reply)">回复</el-button></div></div></div></div></template></li><el-button class="loading_p" type="primary" size="mini" v-if="item.moreValue" :loading="childrenMorelist.loading" @click="changeChildrenMore(item)">加载更多</el-button></ul></div></div></div></div><!-- 一级查看更多 --><el-button type="info" class="moreBtn" :loading="morelist.loading" @click="changeMore" v-if="morelist.value">查看更多评论<i class="el-icon-caret-bottom"></i> </el-button><!-- <div v-else class="more_div">暂无更多评论</div> --><!-- 暂无评论的空状态 --><el-empty :description="emptyText" v-if="comments.length === 0"></el-empty></div>
</template>
<script>
export default {props: {sourceType: {type: String,require: true},articleId: {//评论所属文章 idtype: String},emptyText: {// 评论为空的时候显示的文字type: String,default: "期待你的评论!"},buttonText: {// 按钮文字type: String,default: "评论"},contentLength: {// 评论长度type: Number,default: 150},placeholderText: {// 默认显示文字type: String,default: "请输入最多150字的评论..."}},data() {return {bigLoading: false,userInfor: {},params: {pageNum: "1",pageSize: "5",orderByColumn: "createTime",isAsc: "asc",sourceType: this.sourceType,mainId: "",},pantPageNum: "1", // 父级查看更多total: 0,comments: [], // 获取得到的评论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,loading: false,},childrenMorelist: {index: '2',childrenId: "",childrenPageNum: "1", // 子级查看更多childrenTotal: 0,value: false,loading: false,},};},mounted() {this.userInfor = localStorage.getItem("userInfor") ? JSON.parse(localStorage.getItem("userInfor")) : {};// 获取评论数据this.getCommentList();},computed: {isLogin() {return this.$store.getters.isLogin;},},methods: {chooseEmoji(layer,val) {if(layer) {this.replyContext += val;return;}this.context += val;},// 查看更多评论async changeMore() {this.morelist.loading = true;this.pantPageNum++;this.params.pageNum = this.pantPageNum;console.log("this.params.pageNum",this.params.pageNum);let res = await this.getNewList();res.rows.map(item => {this.$set(item,'publicTotal',false)})this.comments.push(...res.rows);this.morelist.loading = false;this.total = res.total;if(res.total > this.params.pageNum * this.params.pageSize) {this.morelist.value = true;}else {this.morelist.value = false;}},// 加载更多async changeChildrenMore(item) {if(this.childrenMorelist.childrenId && this.childrenMorelist.childrenId != item.id) {this.childrenMorelist.childrenPageNum = "1";}this.childrenMorelist.childrenId = item.id;this.childrenMorelist.loading = true;this.childrenMorelist.childrenPageNum++;this.params.pageNum = this.childrenMorelist.childrenPageNum;this.params.mainId = item.id;let res = await this.getNewList();this.childrenMorelist.childrenTotal = res.total;console.log("res",res);item.commentReplyInfoList.push(...res.rows);this.childrenMorelist.loading = false;if(res.total > this.params.pageNum * this.params.pageSize) {item.moreValue = true;}else {item.moreValue = false;}},load(list) {list += 2},// 唤起文件选择handleClick() {this.$refs.avatar.click();},// 获取本篇文章所有评论async getCommentList() {try {this.comments = [];this.bigLoading = true;// 获取某篇文章下的所有评论const res = await this.$get(`/api/comment/list?pageNum=${this.params.pageNum}&pageSize=${this.params.pageSize}&orderByColumn=${this.params.orderByColumn} desc,auditStatus&isAsc=${this.params.isAsc}&sourceType=${this.params.sourceType}&mainId=${this.params.mainId}&sourceId=${this.$route.query.id}`)this.bigLoading = false;this.comments = res.rows; //评论列表this.total = res.total; //评论总数if(this.total > this.params.pageSize) {this.morelist.value = true;}else {this.morelist.value = false;}this.comments.map(item => {if(item.commentReplyCount > 5) {item.moreValue = true;}else {item.moreValue = false;}this.$set(item,'publicTotal',false)}) } catch (err) {this.bigLoading = false;this.$message.error(err);}},async getNewList() {let res = await this.$get(`/api/comment/list?pageNum=${this.params.pageNum}&pageSize=${this.params.pageSize}&orderByColumn=${this.params.orderByColumn} desc,auditStatus&isAsc=${this.params.isAsc}&sourceType=${this.params.sourceType}&mainId=${this.params.mainId}&sourceId=${this.$route.query.id}`);console.log("res1111",res);return res;},// 控制二级条数显示盒子hanlePublicTotal(item) {item.publicTotal = !item.publicTotal;console.log("item",item);},isShowSecReply(item) {console.log("一级input获取焦点",item);let id = item?.id;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(item, reply) {if(!this.isLogin) {this.$message.warning("请先登录!");return;}let _id = item.id;let replyId = reply?.id;if (replyId) {// 删除二级评论,提交请求到后端this.$confirm('确认删除此评论?', '提示', {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'}).then(() => {this.$put(`/api/comment/${replyId}`).then(async (res) => {if (res.code === 200) {this.params.pageNum = '1';let data = await this.getNewList();console.log("data",data);item.commentReplyCount = data.total;item.commentReplyInfoList.splice(0);item.commentReplyInfoList.push(...data.rows);//this.$message({message: "删除成功",type: "success",});}});}).catch(() => {this.$message({type: 'info',message: '已取消删除'});})} else {// 删除一级评论,提交请求到后端this.$confirm('确认删除此评论?', '提示', {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'}).then(() => {this.$put(`/api/comment/${_id}`).then((res) => {if (res.code === 200) {this.$message({message: "删除成功",type: "success",});this.params.pageNum = '1';this.getCommentList();}});this.total--;if(this.total == this.params.pageSize) {this.morelist.value = false;}}).catch(() => {this.$message({type: 'info',message: '已取消删除'});})}},// 评论添加成功,返回的数据async addComment(item,reply) {console.log(">>>>item",item );if(!this.isLogin) {this.$message.warning("请先登录!");return;}//本地更新评论列表if (item) {// 添加二级评论if (!this.replyContext) {this.$message.warning("评论或留言不能为空哦!");return;}this.addSecond(item,reply);} else {// 添加一级评论,提交数据到后端if (!this.context) {this.$message.warning("评论或留言不能为空哦!");return;}this.addFirst();}this.isShowSec = this.isClickId = "";},addSecond(item,reply) {// 模拟数据提交成功后返回数据let data = {mainId: item.id,parentId: item.id,sourceType: item.sourceType,sourceId: this.$route.query.id, commentContent: this.replyContext //评论内容};if(reply) {data.parentId = reply.id;}this.$post("/api/comment",data).then(async(res) => {if(res.code == 200) {this.params.mainId = item.id;let res = await this.getNewList();if(!item.commentReplyInfoList) {item.commentReplyInfoList = [];}item.commentReplyInfoList.splice(0);item.commentReplyInfoList.push(...res.rows);item.commentReplyCount = res.total;if(res.total > 5) {item.moreValue = true;}this.replyContext = "";console.log("comments",this.comments);}})},addFirst() {// 模拟数据提交成功后返回数据let data = {mainId: '',parentId: '',sourceType: this.sourceType,sourceId: this.$route.query.id, commentContent: this.context //评论内容};this.$post("/api/comment",data).then(async(res) => {if(res.code == 200) {this.params.mainId = '';let res = await this.getNewList();res.rows.map(item => {this.$set(item,'publicTotal',false)})this.comments = res.rows;this.context = "";this.total = res.total;if(res.total > 5) {this.morelist.value = true;}}})},}
};
</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;}.img_width {max-width: 50px;max-height: 50px;border-radius: 50px;font-size: 30px;color: #3339;}.flex_box {padding: 0 5px;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 60px;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);color: #0d74e1;}}.loading_p {cursor: pointer;margin: 3px auto;display: flex;justify-content: center;}}}}.moreBtn {width: 100%;i {font-size: 16px;}}.more_div {display: flex;display: flex;justify-content: center;color: #66666694;font-size: 14px;}::-webkit-scrollbar{width: 8px;height: 5px;background-color: #F5F5F5;}/*定义滚动条轨道 内阴影+圆角*/::-webkit-scrollbar-track{-webkit-box-shadow: inset 0 0 6px #c0c0c0;border-radius: 10px;background-color: #f9f9f9;}/*定义滑块 内阴影+圆角*/::-webkit-scrollbar-thumb{border-radius: 10px;-webkit-box-shadow: inset 0 0 6px #c0c0c0;background-color: #c0c0c0;}
}
</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>

效果如下:

​​​​​​​

这篇关于Vue2+Element 封装评论+表情功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1009675

相关文章

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

Vue和React受控组件的区别小结

《Vue和React受控组件的区别小结》本文主要介绍了Vue和React受控组件的区别小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录背景React 的实现vue3 的实现写法一:直接修改事件参数写法二:通过ref引用 DOMVu

Java实现将HTML文件与字符串转换为图片

《Java实现将HTML文件与字符串转换为图片》在Java开发中,我们经常会遇到将HTML内容转换为图片的需求,本文小编就来和大家详细讲讲如何使用FreeSpire.DocforJava库来实现这一功... 目录前言核心实现:html 转图片完整代码场景 1:转换本地 HTML 文件为图片场景 2:转换 H

C#使用Spire.Doc for .NET实现HTML转Word的高效方案

《C#使用Spire.Docfor.NET实现HTML转Word的高效方案》在Web开发中,HTML内容的生成与处理是高频需求,然而,当用户需要将HTML页面或动态生成的HTML字符串转换为Wor... 目录引言一、html转Word的典型场景与挑战二、用 Spire.Doc 实现 HTML 转 Word1

Vue3绑定props默认值问题

《Vue3绑定props默认值问题》使用Vue3的defineProps配合TypeScript的interface定义props类型,并通过withDefaults设置默认值,使组件能安全访问传入的... 目录前言步骤步骤1:使用 defineProps 定义 Props步骤2:设置默认值总结前言使用T

Debian 13升级后网络转发等功能异常怎么办? 并非错误而是管理机制变更

《Debian13升级后网络转发等功能异常怎么办?并非错误而是管理机制变更》很多朋友反馈,更新到Debian13后网络转发等功能异常,这并非BUG而是Debian13Trixie调整... 日前 Debian 13 Trixie 发布后已经有众多网友升级到新版本,只不过升级后发现某些功能存在异常,例如网络转

基于Java和FFmpeg实现视频压缩和剪辑功能

《基于Java和FFmpeg实现视频压缩和剪辑功能》在视频处理开发中,压缩和剪辑是常见的需求,本文将介绍如何使用Java结合FFmpeg实现视频压缩和剪辑功能,同时去除数据库操作,仅专注于视频处理,需... 目录引言1. 环境准备1.1 项目依赖1.2 安装 FFmpeg2. 视频压缩功能实现2.1 主要功

使用Python实现无损放大图片功能

《使用Python实现无损放大图片功能》本文介绍了如何使用Python的Pillow库进行无损图片放大,区分了JPEG和PNG格式在放大过程中的特点,并给出了示例代码,JPEG格式可能受压缩影响,需先... 目录一、什么是无损放大?二、实现方法步骤1:读取图片步骤2:无损放大图片步骤3:保存图片三、示php

深度解析Python yfinance的核心功能和高级用法

《深度解析Pythonyfinance的核心功能和高级用法》yfinance是一个功能强大且易于使用的Python库,用于从YahooFinance获取金融数据,本教程将深入探讨yfinance的核... 目录yfinance 深度解析教程 (python)1. 简介与安装1.1 什么是 yfinance?

Python脚本轻松实现检测麦克风功能

《Python脚本轻松实现检测麦克风功能》在进行音频处理或开发需要使用麦克风的应用程序时,确保麦克风功能正常是非常重要的,本文将介绍一个简单的Python脚本,能够帮助我们检测本地麦克风的功能,需要的... 目录轻松检测麦克风功能脚本介绍一、python环境准备二、代码解析三、使用方法四、知识扩展轻松检测麦