思路
移动端的上拉加载关键点在于,怎么知道列表已经滚动到最底部了。
当(窗口的高度 + 元素超出上边界的高度) >= 元素高度
时,触底。
关键属性
- windowHeight
窗口的高度,使用
document.documentElement.clientHeight || document.body.clientHeight
获取
- scrollHeight
元素高度,使用
document.documentElement.scrollHeight || document.body.scrollHeight
获取
- scrollTop
元素超出上边界的值,使用
document.documentElement.scrollTop || document.body.scrollTop
获取
实现
首先要实时监听页面滚动,这里在mounted
里给浏览器加入一个scroll
事件,给这个事件一个方法handleScroll
,方便调用它
mounted() {
window.addEventListener("scroll", this.handleScroll, true);
}
在handleScroll
里首先获取到关键属性的值,对比高度即可。在触底时获取当前页数和当前列表数组的长度
ps:这里要使用个延时加载(延时加载传送门),不然滑动屏幕的时候会不断触发方法,去计算高度,浪费性能
handleScroll() {
//这里使用个延时加载,不然滑动屏幕的时候会不断触发方法,去计算高度,浪费性能
let that = this
clearTimeout(this.timer)
that.timer = setTimeout(function () {
scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
let windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
//获取到关键属性的值后,判断即可
if (scrollTop + windowHeight >= scrollHeight) {
console.log("触底");
//在触底时获取当前页数和当前列表数组的长度
let pageNum = that.pageNum;
let length = that.newsList.length;
//对比当前列表长度和列表总数,如果相等,说明没有数据了,否则页数加一,再次调获取列表接口
if (length == that.total) {
// 我也是有底线的
} else {
pageNum++
that.pageNum = pageNum;
that.getNewList();
}
}
}, 500);
}
这里获取列表接口需要一些操作,判断是第一次调接口还是触底调接口
getNewList() {
getNewList(this.pageNum, this.pageSize).then(res => {
if (res.status == 200) {
let newsList = [];
//如果是第一次就直接赋值,否则需要在原数组上拼接新数据
if (this.pageNum == 1) {
newsList = res.data.list;
} else {
newsList = this.newsList.concat(res.data.list);
}
this.total = parseInt(res.data.total) || 0;
this.newsList = newsList;
}
});
},
ps:
页面需要滚动才能触发scroll,所以pageSize
的数量要够一屏,如果一屏可以放10条数据,pageSize
值就要是11