1. 理解scrollTop, offsetHeight, scrollHeight
Dimensions-client.png
Dimensions-offset.png
image.png
2. 加載條件
a. 下拉自動(dòng)加載米奸,就是不斷增加整個(gè)滾動(dòng)區(qū)域的高度(scrollHeight)
b. 下拉移動(dòng)光標(biāo)毫捣,不斷增加ScrollTop,知道接近整個(gè)滾動(dòng)區(qū)的底部時(shí)棺亭,意味著我們馬上需要加載更多數(shù)據(jù),使得整個(gè)滾動(dòng)區(qū)域(crollHeight)變得更高。
<script>
export default {
data() {
return {
scrollTop:0,//滾動(dòng)條位置
offsetHeight:0,//可視區(qū)高
scrollHeight:0,//滾動(dòng)區(qū)域
noMoreData: false
};
},
mounted() {
let _this = this;
window.addEventListener('scroll', _this.bindScroll);
},
watch: {
//觀察滾動(dòng)條位置
scrollTop:function(){
// console.log("當(dāng)前滾動(dòng)條高"+this.scrollTop);
// console.log("可視區(qū)高"+this.offsetHeight);
// console.log("滾動(dòng)條高"+this.scrollHeight);
if (this.scrollHeight <= (this.offsetHeight + this.scrollTop)) {
// 拉取更多數(shù)據(jù)
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