主要逻辑就是监听滚动条距离底部的高度,到达一定距离的时候请求数据。
scroll() {
let isLoading = false
window.onscroll = async () => {
// 变量 scrollHeight 是滚动条的总高度
let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
// 变量 windowHeight 是可视区的高度
let windowHeight = document.documentElement.clientHeight || document.body.clientHeight
// 变量scrollTop为当前页面的滚动条纵坐标位置
let scrollTop = document.documentElement.scrollTop || document.body.scrollTop
// 滚动条到底部得距离 = 滚动条的总高度 - 可视区的高度 - 当前页面的滚动条纵坐标位置
var scrollBottom = scrollHeight - windowHeight - scrollTop
//距离底部500 的时候请求数据
let bottomOfWindow = scrollBottom <= 500;
if (bottomOfWindow && isLoading === false) {
isLoading = true
//开始加载,在这请求数据 ,请求两条数据
for (let i = 0; i < 2; i++) {
++this.page;
if(!await this.request()){
break
}
}
isLoading = false
}
}
},
mounted() {
//监听滚动
this.scroll();
}