开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第5天,查看详情
需求: 最新消息展示在最下面,往上滑动加载历史消息
开发背景: 1.平时默认最新的数据在最上方 2. 最开始搞不懂怎么滑动,平时做的加载更多都是下滑加载更多 3. 一加载数据时,怎么让页面自动滑动到最新消息的消息??
接下来就是把需求一步一步实现,把问题一个一个解决掉:
1. 加载数据问题
其实数据就是当加载第一页时push进去,再上拉加载更多时把数据unshift()进数组的开头即可,代码如下所示:
getList() {
pageList({
page: this.page,
todoType: this.todoType,
sourceType: this.sourceType
})
.then(res => {
console.log('详情结果', res)
let newList = this.list;
this.isMore = res.pages > this.page;
if (this.page == 1) {
res.list.forEach(val => {
newList.push(val);
this.list = newList;
});
this.loading = true
var that = this
that.$nextTick(() => {
setTimeout(() => {
uni.createSelectorQuery().select(".bottomDrop")
.boundingClientRect(function(
res) {
console.log("获取高度", res)
uni.pageScrollTo({
scrollTop: res.height,
duration: 0
});
}).exec()
}, 50)
})
} else {
this.loading = true
res.list.forEach(val => {
newList.unshift(val);
this.list = newList;
});
}
});
},
2. 下滑加载更多 onPullDownRefresh()
注意: 一定要加上uni.stopPullDownRefresh(), 要不页面处在加载中的时间过长
onPullDownRefresh() {
if (this.isMore == 0) {
uni.stopPullDownRefresh()
return false;
} else {
var page = this.page + 1;
this.page = page;
this.getList();
uni.stopPullDownRefresh()
}
},
3.消息页面加载时,自动定位到最新消息
- html页面加上class节点
<view class="bottomDrop"></view>
- 数据加载完成后处理
注意: 一定要加上 that.$nextTick(() => { setTimeout(() => {}, 50) }) 最开始做的时候没有加上回调,数据都加载完成了,但是页面没有动静,还处在最上方,这不符合需求,后来通过打印数据才发现,uni.pageScrollTo()执行的时机不对
that.$nextTick(() => {
setTimeout(() => {
uni.createSelectorQuery().select(".bottomDrop")
.boundingClientRect(function(
res) {
console.log("获取高度", res)
uni.pageScrollTo({
scrollTop: res.height,
duration: 0
});
}).exec()
}, 50)
})