一個(gè)需要判斷的地方就是加載中再次觸發(fā)滾動(dòng)的時(shí)候,不要獲取數(shù)據(jù)。
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>列表無限加載</title> <style>  * {   margin: 0;   padding: 0;  }  li {   height: 50px;   border-bottom: 1px solid #c7c7c7;   list-style: none;   line-height: 50px;   padding-left: 30px;  } </style></head><body> <div id="unlimitedList">  <ul>   <li v-for="item in list">{{ item }}</li>   <li :style="{display: loading ? 'initial' : 'none'}">Loading......</div>  </ul> </div> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script> <script>  function fetch(from, size = 20) { // 模擬后臺(tái)獲取數(shù)據(jù)   console.log('獲取數(shù)據(jù) 傳入: ', { from, size });   let data = [];   let total = 98;   size = Math.min(size, total - from + 1);   for (let i = 0; i < size; i++) {    data.push(`列表項(xiàng)${from + i}`);   }   let ret = { data, total };   return new Promise(function (resolve, reject) {    setTimeout(() => {     console.log('獲取數(shù)據(jù) 返回: ', ret);     resolve(ret);    }, 500);   })  }  new Vue({   el: '#unlimitedList',   data: {    list: [],    loading: true,  // 數(shù)據(jù)加載中    allLoaded: false // 數(shù)據(jù)已經(jīng)全部加載   },   methods: {    getData() {     this.loading = true; // 顯示加載中的標(biāo)識(shí)     fetch(this.list.length + 1).then(res => {      this.list.splice(this.list.length, 0, ...res.data); // 將新獲取到的數(shù)據(jù)連接到 this.list (vue 能檢測到 splice() 函數(shù)      this.loading = false; // 加載結(jié)束 取消加載中顯示      if (this.list.length === res.total) {       this.allLoaded = true;      }     })    },    onScroll(e) {     if (this.loading || this.allLoaded) return;     let top = document.documentElement.scrollTop || document.body.scrollTop; // 滾動(dòng)條在Y軸上的滾動(dòng)距離     let vh = document.compatMode == 'CSS1Compat' ? document.documentElement.clientHeight : document.body.clientHeight; // 瀏覽器視口的高度     let height = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); // 文檔的總高度     if (top + vh >= height) { // 滾動(dòng)到底部      this.getData(); // 如果已經(jīng)滾到底了 獲取數(shù)據(jù)     }    }   },   created() {    this.getData();    window.addEventListener('scroll', this.onScroll);   },   destroyed () {    window.removeEventListener('scroll', this.onScroll);   }  }) </script></body></html>總結(jié)
以上所述是小編給大家介紹的Vue實(shí)現(xiàn)一個(gè)無限加載列表功能,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)錯(cuò)新站長站網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選