分页是一种将数据分段展现给用户的一种技术。现如今一般有两种方式,一种是前端获取所有记录并存在内存中,然后将部分数据分页显示给用户。另一种是前端多次像后端获取数据,每次只获取部分数据。
在ionic框架中,通过InfiniteScroll可以方便地进行下拉加载,实现分页效果,如下图所示
具体代码如下:
html文件
<ion-content>
<ion-infinite-scroll (ionInfinite)="doInfinite($event)">
<ion-infinite-scroll-content
loadingSpinner="bubbles"
loadingText="加载中">
</ion-infinite-scroll-content>
</ion-infinite-scroll>
</ion-content>
其中spinner有多种样式,包括:ios、ios-small、bubbles、circles、crescent、dots 等,可以自己挑一个最适合的
官方文档上也有一个waitfor的InfiniteScroll,将所有数据加载完毕之后再显示
ts文件
以第二种分页方式为例,直接手写的,>_<||| ,请不要直接跑
//import...
@Component({...})
export class NewsFeedPage {
items = []; //定义要在页面显示的数组
pageNum = 0;
recordOrder = 0;
constructor() {
}
//在进入也面前加载十条数据
ionViewDidLoad(){
//这边后端是用ssh做的,httpservice是我自己定义的,通过promise异步操作进行post或者get数据,获得json格式数据,pageNum传给后端
this.httpService.get(this.url + "一个action",pageNum)
.then(res=>{
for(this.recordOrder = 0; this.recordOrder < this.getJsonLength(res);this.recordOrder++){
//在这之前请通过后端返回的数据判断数据是否加载完毕,若加载完毕及时结束循环
//将十条记录放入items里面
this.items.push(res[this.recordOrder]);
}
}).catch((err:any)=>{
console.log(err);
});
}
}
doInfinite(infiniteScroll) {
console.log('Begin async operation');
//加载1秒
setTimeout(() => {
this.httpService.get(this.url + "一个action",pageNum)
.then(res=>{
for(this.recordOrder = 0; this.recordOrder < this.getJsonLength(res);this.recordOrder++){
//在这之前请通过后端返回的数据判断数据是否加载完毕,加载完毕请添加infiniteScroll.enable(false);并结束循环
//将十条记录放入items里面
this.items.push(res[this.recordOrder]);
}
}).catch((err:any)=>{
console.log(err);
});
console.log('Async operation has ended');
//十条数据加载完毕
infiniteScroll.complete();
}, 1000);
}
}
spinner相关资料:https://ionicframework.com/docs/api/components/spinner/Spinner/
InfiniteScroll相关资料:https://ionicframework.com/docs/api/components/infinite-scroll/InfiniteScroll/