uniapp评论区
uniapp 评论区实现方法
基础评论区结构
使用 scroll-view 组件实现滚动列表,搭配 v-for 渲染评论项。每条评论包含用户头像、昵称、内容和时间戳。
<template>
<scroll-view scroll-y class="comment-container">
<view v-for="(item,index) in comments" :key="index" class="comment-item">
<image :src="item.avatar" mode="aspectFill"></image>
<view class="content">
<text class="username">{{item.nickname}}</text>
<text class="text">{{item.content}}</text>
<text class="time">{{item.time}}</text>
</view>
</view>
</scroll-view>
</template>
数据加载与分页
通过 onReachBottom 生命周期实现分页加载,配合 loading 状态防止重复请求。
data() {
return {
comments: [],
page: 1,
loading: false
}
},
methods: {
loadComments() {
if(this.loading) return;
this.loading = true;
uni.request({
url: 'API_URL',
data: { page: this.page },
success: (res) => {
this.comments = [...this.comments, ...res.data.list]
this.page++
},
complete: () => this.loading = false
})
}
}
发表评论功能
底部固定输入框结合 textarea 和按钮,提交时验证内容非空并调用接口。
<view class="input-area">
<textarea v-model="commentText" placeholder="说点什么..."></textarea>
<button @click="submitComment">发送</button>
</view>
methods: {
submitComment() {
if(!this.commentText.trim()) return uni.showToast({title:'内容不能为空'});
uni.request({
url: 'POST_API_URL',
method: 'POST',
data: { content: this.commentText },
success: () => {
this.commentText = '';
this.page = 1;
this.comments = [];
this.loadComments();
}
})
}
}
高级功能实现
回复功能设计 点击评论项时显示回复输入框,记录当前回复的评论ID。
data() {
return {
replyTo: null,
replyText: ''
}
},
methods: {
showReply(commentId) {
this.replyTo = commentId;
},
submitReply() {
// 提交时携带this.replyTo作为父评论ID
}
}
点赞与互动 为每条评论添加点赞按钮,记录用户互动状态。
<view class="actions">
<text @click="likeComment(item.id)">{{item.likeCount}}</text>
<text @click="showReply(item.id)">回复</text>
</view>
图片/表情支持
使用 uni.chooseImage 实现图片上传,表情需预先定义表情库。
chooseImage() {
uni.chooseImage({
count: 3,
success: (res) => {
this.uploadImages(res.tempFilePaths)
}
})
}
性能优化建议
图片懒加载
使用 lazy-load 属性延迟加载非可视区域图片
<image lazy-load :src="item.avatar"></image>
数据缓存策略
对已加载的评论数据使用 uni.setStorage 进行本地缓存,下次打开优先显示缓存内容
虚拟列表优化
超长列表建议使用 recycle-list 组件替代常规渲染,大幅减少内存占用
样式设计示例
.comment-container {
height: 70vh;
padding: 20rpx;
}
.comment-item {
display: flex;
margin-bottom: 30rpx;
}
.comment-item image {
width: 80rpx;
height: 80rpx;
border-radius: 50%;
}
.input-area {
position: fixed;
bottom: 0;
width: 100%;
background: #fff;
padding: 20rpx;
box-sizing: border-box;
}






