uni-app模仿微信聊天功能,上拉加载历史消息位置保持不变
uni-app模仿微信聊天上拉加载更多消息
·
uni-app模仿微信聊天功能,上拉加载历史消息位置保持不变
不废话,直接上图,依旧存在抖动问题,H5不明显,app比较明显。
标签
scroll-view
标签属性
scroll-y 允许纵向滚动
upper-threshold 距顶部/左边多远时(单位px),触发 scrolltoupper 事件
scroll-into-view 值应为某子元素id(id不能以数字开头)。设置哪个方向可滚动,则在哪个方向滚动到该元素
@scrolltoupper 滚动到顶部/左边,会触发 scrolltoupper 事件
HTML部分
<scroll-view class="scroll-view_H" :style="{ height: centerHeight + 'px' }" scroll-y upper-threshold="20"
@scrolltoupper="scrollTop" scroll-anchoring="true" :scroll-into-view="childrenId">
<view class="chat_content_li" v-for="(item,index) in chatList" :key="index" :id="'s' + item.id"></view>
</scroll-view>
特别注意的是,scroll-into-view的值为id,且id不能是数字开头;后端传来的数据中id为数字类型,所以这里我们把从后端拿来的数据渲染后将id从新更改为“s+item.id”。
JS部分
获取消息列表数据
// 请求群聊记录
getMessageList() {
var that = this;
uni.showLoading({
title: '加载中...'
})
uni.request({
url: that.url,
method: "GET",
data: {
pageNum: that.pageNum,
pageSize: 20,
},
success(res) {
uni.hideLoading();
if (res.data.code == 200) {
that.chatList = res.data.rows.concat(that.chatList)
that.setChildrenId(res.data.rows);
}
},
fail() {
uni.hideLoading();
}
})
},
这里的pageNum为分页,初始值为1;pageSize为一页有多少条消息,在h5上pageSize值为10正常,但在app中只渲染出来10条消息的高度并不能超出手机整个屏幕,所以无法触发滑动,进而无法触发@scrolltoupper事件,可按自己所需更改。
每次调用该函数,都会将新得到的数组添加到以前的老数组;需要注意的是,是将新数组添加到老数组的前面,而并非像上拉加载更多那种将新数组添加到老数组的后面。
数据赋值后,调用that.setChildrenId(res.data.rows),设置节点id。
setChildrenId 设置节点id
// 设置节点Id
setChildrenId(list) {
var that = this;
if (that.pageNum == 1) { //通过页码来判断用户是否首次进入
that.$nextTick(() => {
if (list.length != 0) {
let index = list.length - 1;
that.childrenId = 's' + list[index].id;
console.log(that.childrenId, "首次进入需要滑动到页面最底部")
}
});
} else {
that.$nextTick(() => {
console.log(that.topIndex, "that.topId")
that.childrenId = 's' + that.topId
console.log(that.childrenId, "下拉刷新")
});
}
},
@scrolltoupper 滚动到顶部事件
// 下拉加载更多聊天内容
scrollTop(e) {
this.pageNum = this.pageNum + 1;
this.topId = this.chatList[0].id; //数据没改变前,记录最上方(第一条数据)的id,需要将它设置为节点
console.log(this.topId)
this.getMessageList(); //请求群聊记录
},
每次下拉都会记录当前数据的第一条数据id,然后请求群聊记录,并将新老数组合并,并设置新的childrenId,来实现上拉加载历史消息位置保持不变。
更多推荐
已为社区贡献1条内容
所有评论(0)