經過屢次爬坑,發現了這些監聽滾動來加載更多的組件的共同點,html
由於這些加載更多的方法是綁定在須要加載更多的內容的元素上的,vue
因此是進入頁面則直接觸發一次,當監聽到滾動事件以後,繼續加載更多,svg
因此對於無限滾動加載不須要寫首次載入列表的函數,函數
代碼以下:ui
html: //父組件 <div v-infinite-scroll="loadMore" infinite-scroll-disabled="loading" infinite-scroll-distance="1000"> <LifeLists :loadingTextBtn="loadingTextBtn" :loadingText="loadingText" :loadingComplete="loadingComplete" :lifeList="lifeList"></LifeLists> </div> //LifeLists組件: <LifeListItem :lists="lifeList"></LifeListItem> <div class="loading-text" v-show="{loadingTextBtn:true}"> <span v-text="loadingText"></span> <mt-spinner v-if="(loadingComplete==false)" type="snake" :size="16"></mt-spinner> </div> //LifeListItem組件: <div id="lifeListItemBox"> <router-link v-for="(item,index) in lists" :to="{name:'lifeDetails',params:{id:item.id}}" :key="index"> <div class="lifeListItem1" v-if="(item.status=='online')"> <div v-if="(item.hasPrice==true)"> <div class="title1">{{item.title}}</div> <div class="price"> <b class="now"><span class="unit">{{item.monetaryUnit}}</span>{{item.price}}</b> </div> </div> <div v-else class="title2">{{item.title}}</div> <div class="info"> 發佈於{{formatTime(item.createAt)}} {{item.countryName}} {{item.cityName}} </div> <div class="imageList"> <img :src="img" alt="" v-for="(img,index) in item.photos"> </div> <div class="content">{{item.detail}}</div> <div class="listBar"> <div class="iconBox"> <svg class="icon icon-dianzan" aria-hidden="true"> <use xlink:href="#icon-dianzan"></use> </svg> {{item.like}} </div> <div class="iconBox"> <svg class="icon icon-pinglun2" aria-hidden="true"> <use xlink:href="#icon-pinglun2"></use> </svg> {{item.commentCount}} </div> </div> </div> </router-link> </div> vue.js //data: page:0, size:10, loadingTextBtn:false, loadingText:"努力加載中", loadingComplete:false, refreshComplete:false, city:"", country:"" //methods: loadMore() { this.loading = true; this.loadingTextBtn=true; if(parseInt(this.page)==0){ this.$store.dispatch('loadMoreLifeList',{city:"紐約",country:"美國",category:"",page:this.page,size:this.size}); this.page++; }else if(parseInt(this.page)>0&&parseInt(this.page)<parseInt(this.totalPages)){ setTimeout(() => { // this.$store.dispatch('loadMoreLifeList',{city:this.city,country:this.country,category:"",page:this.page,size:this.size}) this.$store.dispatch('loadMoreLifeList',{city:"紐約",country:"美國",category:"",page:this.page,size:this.size}); this.page++; }, 1000); }else{ this.loadingText="已所有加載完成"; this.loadingComplete=true; this.loading = false; } },
這裏重要的是判斷,噹噹前頁面爲0的時候,即第一頁的時候,不須要setTimeout定時器,直接請求加載,當加載更多的時候能夠加個定時器。this
網上找到不少mint-ui 的loadmore組件來實現上拉加載更多,因爲上拉觸發相應的加載更多事件,因此當進入頁面的時候應該不會自動載入數據,則這裏能夠加一個獲取第一頁數據的函數。spa