基于 Vue.js 的移动端组件库mint-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; } },
网上找到很多mint-ui 的loadmore组件来实现上拉加载更多,由于上拉触发相应的加载更多事件,所以当进入页面的时候应该不会自动载入数据,则这里可以加一个获取第一页数据的函数。