1. 程式人生 > >Vue滾動底部 載入更多的功能說明

Vue滾動底部 載入更多的功能說明

今天,閒來無事就寫了一個關於Vue滾動底部載入更多的功能,話不多說,直接上程式碼!##先宣告我自己使用cli3寫的

做這個功能最主要的就是獲取3個值 scrollTop,clientHeight,scrollHeight 之後判斷3值之間的關係效果自然就出來了

  scrollTop為滾動條在Y軸上的滾動距離。        
  clientHeight為內容可視區域的高度。        
  scrollHeight為內容可視區域的高度加上溢位(滾動)的距離。  

我在Methods中寫了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; }, //文件的總高度 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; }, getWindowHeight(){   var windowHeight = 0;   if(document.compatMode == “CSS1Compat”){     windowHeight = document.documentElement.clientHeight;   }else{     windowHeight = document.body.clientHeight;   }   return windowHeight; }

當然你也可以寫一個工具類封裝這些函式

之後在mounted中寫下面的方法出發scroll事件

window.addEventListener(‘scroll’, this.handleScroll)

最後要做的就是寫handleScroll這個方法了,滾動到底部要幹什麼

handleScroll(){ if(this.getScrollTop() + this.getWindowHeight() >= this.getScrollHeight()){ for(var i = 0; i <10; i++) { this.data.push(this.data[this.data.length-1]+1); } console.log(this.data) }

如果想看到明顯的效果可以給它設定一個定時器

handleScroll(){ if(this.getScrollTop() + this.getWindowHeight() >= this.getScrollHeight()){ setTimeout(() => { for(var i = 0; i <10; i++) { this.data.push(this.data[this.data.length-1]+1); //我data中的資料是1-10的陣列 每次拉到底部就加10條資料 10=>20=>30 } }, 2000) console.log(this.data) }

template中隨便寫點

<div:key=“index” v-for="(data,index) in data"> //這裡寫迴圈的內容 </div.>

最後的效果就是每次拉到底部 就多出10條資料