1. 理解scrollTop, offsetHeight, scrollHeight
![](https://img.haomeiwen.com/i7967724/39787e25182687c9.png)
![](https://img.haomeiwen.com/i7967724/1e9d28c229e417c4.png)
![](https://img.haomeiwen.com/i7967724/0d388d76805cd198.png)
2. 加载条件
a. 下拉自动加载,就是不断增加整个滚动区域的高度(scrollHeight)
b. 下拉移动光标,不断增加ScrollTop,知道接近整个滚动区的底部时,意味着我们马上需要加载更多数据,使得整个滚动区域(crollHeight)变得更高。
<script>
export default {
data() {
return {
scrollTop:0,//滚动条位置
offsetHeight:0,//可视区高
scrollHeight:0,//滚动区域
noMoreData: false
};
},
mounted() {
let _this = this;
window.addEventListener('scroll', _this.bindScroll);
},
watch: {
//观察滚动条位置
scrollTop:function(){
// console.log("当前滚动条高"+this.scrollTop);
// console.log("可视区高"+this.offsetHeight);
// console.log("滚动条高"+this.scrollHeight);
if (this.scrollHeight <= (this.offsetHeight + this.scrollTop)) {
// 拉取更多数据
return this.getMoreData();
}
}
},
methods: {
bindScroll(){
this.scrollTop= document.documentElement.scrollTop;
this.scrollHeight=document.documentElement.scrollHeight;
this.offsetHeight=document.documentElement.offsetHeight;
}
}
}
</script>
参考:
https://developer.mozilla.org/en-US/docs/Web/API/Element/clientTop#Notes
https://imweb.io/topic/57c5409e808fd2fb204eef52
网友评论