uniapp评论区
uniapp 评论区的实现方法
使用 scroll-view 组件实现滚动加载
在 template 中添加 scroll-view,设置 scroll-y 属性允许纵向滚动。通过 @scrolltolower 事件监听滚动到底部,触发加载更多评论的逻辑。示例代码:
<scroll-view scroll-y @scrolltolower="loadMore">
<view v-for="(comment, index) in comments" :key="index">
{{ comment.content }}
</view>
</scroll-view>
分页加载数据
在 script 中定义分页参数和加载方法。初始化时调用 getComments 加载第一页数据,滚动到底部时触发 loadMore 加载下一页。示例逻辑:
data() {
return {
comments: [],
page: 1,
pageSize: 10,
hasMore: true
}
},
methods: {
async getComments() {
const res = await api.getComments({ page: this.page, pageSize: this.pageSize });
this.comments = [...this.comments, ...res.data.list];
this.hasMore = res.data.hasMore;
},
loadMore() {
if (this.hasMore) {
this.page++;
this.getComments();
}
}
}
评论输入框布局
在页面底部固定定位输入框,使用 uni-keyboard 或自定义输入组件。示例结构:
<view class="input-container">
<input v-model="newComment" placeholder="请输入评论" />
<button @click="submitComment">发送</button>
</view>
<style>
.input-container {
position: fixed;
bottom: 0;
width: 100%;
padding: 10px;
background: #fff;
}
</style>
提交评论逻辑
调用后端接口提交数据,成功后刷新列表或局部更新。示例方法:
async submitComment() {
if (!this.newComment.trim()) return;
await api.addComment({ content: this.newComment });
this.newComment = '';
this.page = 1;
this.comments = [];
this.getComments();
}
优化用户体验
- 添加加载状态提示(如
uni.showLoading) - 支持图片/表情评论时可使用
uni.chooseImage选择图片 - 长按评论弹出操作菜单(删除、回复等)
注意事项
- 滚动加载需注意数据去重和页码重置问题
- 输入框在 iOS 上可能需要额外处理键盘遮挡问题
- 列表渲染大量数据时建议使用虚拟列表优化性能
通过以上方法可实现基础的评论区功能,根据实际需求可扩展点赞、回复子评论等交互。







