uniapp评论组件
uniapp评论组件实现方法
评论列表渲染
使用v-for指令循环渲染评论列表,结合uni-list和uni-list-item组件展示每条评论内容。示例代码:
<uni-list>
<uni-list-item v-for="(item, index) in commentList" :key="index">
<template v-slot:header>
<view class="comment-header">
<image :src="item.avatar" mode="aspectFill"></image>
<text>{{item.nickname}}</text>
</view>
</template>
<view class="comment-content">{{item.content}}</view>
<template v-slot:footer>
<view class="comment-footer">
<text>{{item.createTime}}</text>
<uni-icons type="chat" @click="replyComment(item)"></uni-icons>
</view>
</template>
</uni-list-item>
</uni-list>
评论输入区域
通过uni-easyinput和uni-section组件构建输入区域,底部固定定位确保随时可访问:
<view class="input-fixed">
<uni-section title="发表评论" type="line">
<uni-easyinput
v-model="commentContent"
placeholder="请输入评论内容"
:styles="inputStyle">
</uni-easyinput>
<button @click="submitComment">提交</button>
</uni-section>
</view>
数据交互处理
在脚本部分实现评论提交和列表加载逻辑,注意处理分页和网络请求:
export default {
data() {
return {
commentList: [],
commentContent: '',
page: 1,
pageSize: 10
}
},
methods: {
async loadComments() {
const res = await uni.request({
url: '/api/comments',
data: { page: this.page, pageSize: this.pageSize }
})
this.commentList = [...this.commentList, ...res.data.list]
},
async submitComment() {
if(!this.commentContent.trim()) return
await uni.request({
url: '/api/comment',
method: 'POST',
data: { content: this.commentContent }
})
this.commentContent = ''
this.page = 1
this.loadComments()
}
},
onLoad() {
this.loadComments()
}
}
样式优化
使用CSS增强交互体验,包括输入框固定、评论项间距等:
.input-fixed {
position: fixed;
bottom: 0;
width: 100%;
background: #fff;
z-index: 999;
}
.comment-header {
display: flex;
align-items: center;
}
.comment-header image {
width: 40px;
height: 40px;
border-radius: 50%;
margin-right: 10px;
}
.comment-content {
padding: 10px 0;
}
功能扩展建议
- 添加图片上传功能,使用
uni.chooseImage实现多图评论 - 实现点赞功能,通过
uni-icons显示点赞状态 - 增加评论回复嵌套显示,使用递归组件处理层级关系
- 添加@用户功能,配合
textarea的@input事件实现用户匹配 - 集成emoji选择器,使用第三方插件如
emoji-picker组件
性能优化方案
- 实现虚拟列表加载,使用
uni-list的upper-threshold和lower-threshold属性 - 添加数据缓存,通过
uni.setStorage保存已加载评论 - 使用节流函数控制频繁提交
- 对长列表进行分片渲染,避免一次性渲染过多DOM节点
跨平台适配
-
通过条件编译处理平台差异:
// #ifdef H5 const inputStyle = { backgroundColor: '#f5f5f5' } // #endif // #ifdef MP-WEIXIN const inputStyle = { backgroundColor: '#fff' } // #endif -
针对不同平台调整布局样式
-
处理各平台键盘弹出事件差异,使用
uni.onKeyboardHeightChange监听高度变化






