上拉內容區域,拉到底部實現分頁功能,向後端請求更多數據加載到頁面上vue
vue項目,使用純js實現,網上顯示了不少插件能夠實現,我使用了幾個,都不是我須要的效果,可能沒研究明白,沒辦法只能原生實現,具體實現思路以下~後端
思路:經過滾動條判斷是否到內容底部 => 到底部後向後臺請求下一頁得數據 => 將請求得新數據拼接在老數據上 函數
特別:須要判斷請求的頁數是否爲第一頁,若是是第一頁不要拼接this
怎麼判斷滾動條是否到最底部:
三個關鍵的點:插件
1:滾動條距離頂部的距離:document.documentElement.scrollTop||document.body.scrollTop圖片
2:當前窗口內容的可視區域:document.documentElement.clientHeight || document.body.clientHeighget
3:滾動條內容的總高度:document.documentElement.scrollHeight||document.body.scrollHeightconsole
一個關鍵函數:後臺
一個監聽滾動函數:window.addEventListener('scroll',()=>{})cli
一個斷定的等式:滾動條距離頂部 + 窗口可視區域 == 滾動條內容總高度,此時能夠斷定滾動條已經滾動到最底部
created(){
window.addEventListener('scroll',()=>{
// console.log('滾動條距離頂部'+document.documentElement.scrollTop||document.body.scrollTop);
// console.log('可視區域'+document.documentElement.clientHeight ||document.body.clientHeight);
// console.log('滾動條內容的總高度'+document.documentElement.scrollHeight||document.body.scrollHeight);
let scrollTop = document.documentElement.scrollTop||document.body.scrollTop ;
let clientHeight = document.documentElement.clientHeight || document.body.clientHeight ;
let scrollHeight = document.documentElement.scrollHeight||document.body.scrollHeight ;
if(scrollTop+clientHeight == scrollHeight){
console.log("到底部了")
this.handleScroll();
}
});
}
handleScroll(){
if(this.button){
setTimeout(()=>{
this.button = false ; //設置一個按鈕,是否能夠上拉獲取數據,寫在data中
this.page += 1; //獲取下一頁的數據
this.getlist(); //向後端獲取數據
},500)
}
},
上面代碼只是其中部分代碼,主要是側重判斷滾動條滾動到最下方
其中還有好多細節,好比樣式中還寫了,滾動到最下方以後會有一個加載中的圖片,和文字
若是全部數據都加載完成後,顯示「數據所有加載完成」,這些只須要簡單的經過v-if來判斷什麼時候顯示便可,該例子中很少寫了~