uniapp评论组件
uniapp评论组件实现方法
基础评论列表布局
使用<scroll-view>和v-for渲染评论列表,结合<view>和CSS实现基础布局:
<scroll-view scroll-y style="height: 500rpx;">
<view v-for="(item, index) in commentList" :key="index" class="comment-item">
<image :src="item.avatar" mode="aspectFill" class="avatar"></image>
<view class="content">
<text class="username">{{item.username}}</text>
<text class="text">{{item.content}}</text>
<text class="time">{{item.createTime}}</text>
</view>
</view>
</scroll-view>
评论数据格式示例
推荐的数据结构包含用户信息和评论内容:
commentList: [
{
id: 1,
avatar: '/static/avatar/1.jpg',
username: '用户A',
content: '这个产品很好用',
createTime: '2023-05-20 10:30'
},
{
id: 2,
avatar: '/static/avatar/2.jpg',
username: '用户B',
content: '性价比很高,推荐购买',
createTime: '2023-05-21 14:15'
}
]
发表评论功能实现
底部固定输入栏组件实现:
<view class="comment-input-box">
<input
v-model="commentText"
placeholder="请输入评论内容"
@confirm="submitComment"
/>
<button @click="submitComment">发送</button>
</view>
提交评论逻辑处理:
methods: {
submitComment() {
if (!this.commentText.trim()) return uni.showToast({ title: '内容不能为空', icon: 'none' });
const newComment = {
id: Date.now(),
avatar: '/static/avatar/default.jpg',
username: '当前用户',
content: this.commentText,
createTime: this.formatTime(new Date())
};
this.commentList.unshift(newComment);
this.commentText = '';
},
formatTime(date) {
return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
}
}
样式优化建议
通过CSS增强视觉效果:
.comment-item {
display: flex;
padding: 20rpx;
border-bottom: 1rpx solid #eee;
}
.avatar {
width: 80rpx;
height: 80rpx;
border-radius: 50%;
}
.content {
flex: 1;
margin-left: 20rpx;
}
.username {
font-weight: bold;
margin-right: 15rpx;
}
.time {
color: #999;
font-size: 24rpx;
display: block;
margin-top: 10rpx;
}
.comment-input-box {
position: fixed;
bottom: 0;
width: 100%;
display: flex;
padding: 20rpx;
background: #fff;
box-sizing: border-box;
}
高级功能扩展
实现回复功能的数据结构:
commentList: [
{
id: 1,
// ...其他字段
replies: [
{
id: 101,
targetUser: '用户A',
content: '谢谢你的回复',
createTime: '2023-05-20 11:00'
}
]
}
]
分页加载逻辑示例:
onReachBottom() {
if (this.loading || !this.hasMore) return;
this.loading = true;
uni.showLoading({ title: '加载中' });
this.page++;
this.fetchComments();
},
fetchComments() {
// 模拟API请求
setTimeout(() => {
const newData = [...]; // 获取新数据
this.commentList = [...this.commentList, ...newData];
this.hasMore = newData.length >= 10;
this.loading = false;
uni.hideLoading();
}, 800);
}






