vue里某一元素添加滾動事件並上拉加載更多數據


當你並不是整頁滾動,而是頁面中擁有一個fixed固定的頭部時

<div class="body-container" style="height: 300px" @scroll="scrollEvent">

  < div style = "height: 200px" ></ div >
  < div style = "height: 200px" ></ div >
  < div style = "height: 200px" ></ div >
</ div >
 
重點:只要我能讓<div class="body-container" @scroll="scrollEvent">擁有固定高度,就能觸發滾動事件了。
 
接下來添加滾動事件
export default {
  name: 'demo' ,
  data () {
   return {
   msg: '' ,
   }
  },
  methods: {
   scroll(e){
   //滾動的像素+容器的高度>可滾動的總高度-100像素
   if (e.srcElement.scrollTop+e.srcElement.offsetHeight>e.srcElement.scrollHeight-100){
    this .loadMore(); //加載更多
   }
   },
  }
}
 
這樣就能比較清晰的判斷是否滾動到了底部。但是如果僅僅這樣寫,當滾動到底部100px內時,會觸發很多次加載更多,所以我們需要增加一些判斷條件
 
methods: {
   scroll(e){
   // !this.moreLoading 沒有在加載狀態,觸發加載更多時,把this.moreLoading置未true
   // !this.noMore 沒有更多的狀態為false,當我們取到的數據長度小於1頁的數量時,就沒有更多了數據了,把 this.noMore置為true,這樣就不會觸發無意義的加載更多了
   if (e.srcElement.scrollTop+e.srcElement.offsetHeight>e.srcElement.scrollHeight-100 && ! this .moreLoading && ! this .noMore){
    this .loadMore();
   }
   },
  }
 
僅為自己學習記錄筆記
原文地址:https://www.jb51.net/article/171961.htm


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM