什么是无限滚动
无限滚动允许用户在滚到到页面底部时,自动获取下一页内容,无需用户手动点击下一页按钮
无限滚动的代码实现示例
data() {
return {
infoList:[],//用于接收数据信息
pageNum:1,//第几页的数据
pageSize:15,//一次获取几条数据
loadStatus:'loading',//加载状态
isLoadMore:false, //是否加载中
contentText: {
contentdown: '更多',
contentrefresh: '加载中',
contentnomore: '无更多信息'
}
},
mounted() {
this.infoList=[];
this.pageNum=1;
this.getInfo();
},
onReachBottom(){ //上拉触底函数
if(!this.isLoadMore){ //此处判断,上锁,防止重复请求
this.isLoadMore=true;//开启加载状态,让用户知道正在查询
this.pageNum+=1;//每次上拉请求新的一页
this.getInfo();//触发加载数据函数
}
},
getInfo(){
this.$common.getApi('xxx/xxxx/page',{
"pageNum":this.pageNum,
"pageSize":this.pageSize
},'POST').then(res=>{
if(res.success){
if(res.page.list){
this.infoList=this.infoList.concat(res.page.list)//返回的数据列表累加到原有的展示数组里
if(res.page.list.length<this.pageSize){ //判断接口返回数据量小于请求数据量,则表示此为最后一页
this.isLoadMore=true
this.loadStatus='nomore'
}else{
this.isLoadMore=false
}
}else{
this.isLoadMore=true
this.loadStatus='nomore'
}
}else{
this.isLoadMore=false
if(this.pageNum>1){
this.pageNum-=1//触发此函数前pageNum值已加一,请求数据失败,则应进行减一
}
}
}).catch(res=>{
});
}
无限滚动一般步骤
1、监听滚动事件
2、判断滚动位置,确定用户是否已经滚动到页面底部
3、触发加载数据,一但判断用户已经滚动到页面底部,调用接口,触发加载新的数据
4、处理数据,获取到新数据后,将其处理并添加都已有内容,以实现无缝加载效果
5、更新滚动状态,在数据加载完成后,更新滚动状态,以便用户继续滚动时再次触发加载下一页数据的过程