首先需要明確3個定義:
文檔高度:整個頁面的高度
可視窗口高度:你看到的瀏覽器可視屏幕高度
滾動條滾動高度: 滾動條下滑過的高度
當 文檔高度 = 可視窗口高度 + 滾動條高度 時,滾動條正好到底。
首先在mounted中添加監聽:window.addEventListener('scroll', this.scrollFn); // 監聽scroll
然后創建3個函數分別獲取文檔高度、可視窗口高度、滾動條高度:
//文檔高度
getScrollTop(){
var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
if(document.body){
bodyScrollTop = document.body.scrollTop;
}
if(document.documentElement){
documentScrollTop = document.documentElement.scrollTop;
}
scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
return scrollTop;
}
//可視窗口高度
getWindowHeight(){
var windowHeight = 0;
if(document.compatMode == "CSS1Compat"){
windowHeight = document.documentElement.clientHeight;
}
else{
windowHeight = document.body.clientHeight;
}
return windowHeight;
}
//滾動條高度
getScrollHeight(){
var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
if(document.body){
bodyScrollHeight = document.body.scrollHeight;
}
if(document.documentElement){
documentScrollHeight = document.documentElement.scrollHeight;
}
scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
return scrollHeight;
}
然后在scrollFn函數中判斷:
scrollFn(){
if(this.getScrollTop() + this.getWindowHeight() == this.getScrollHeight()){
這里執行動態獲取數據的函數
}
}
最后記得銷毀監聽:
destroyed() {
window.removeEventListener('scroll', this.scrollFn); // 銷毀監聽
}
如此即可實現滑動加載更多。