IONIC 頁面下拉載入新的資料(ion-infinite-scroll的使用)
阿新 • • 發佈:2018-11-17
類似於淘寶,瀏覽商品時,每次下拉都會刷新出新的資料(需要配合分頁使用,分頁在我部落格中有介紹:https://mp.csdn.net/postedit/83584133)
html頁面
<ion-header> <ion-navbar color="light"> <ion-title>item-detailds</ion-title> </ion-navbar> </ion-header> <ion-content> <!--資料列表--> <ion-list no-lines> <ion-card *ngFor="let item of items"> <h2> <ion-icon name="ios-keypad"></ion-icon> <span> {{item.ItemID}} </span> </h2> <p> <span>{{item.ItemType}}</span> <span>{{item.Qty}}</span> </p> <p> <span>{{item.Name}}</span> </p> </ion-card> </ion-list> <!--下拉時,載入新的資料--> <ion-infinite-scroll (ionInfinite)="doInfinite($event)"> <ion-infinite-scroll-content loadingSpinner="crescent" loadingText="loadingmore"> </ion-infinite-scroll-content> </ion-infinite-scroll> <!--載入完全部資料後--> <p *ngIf="BolNoMoreData" text-center>Not More Data...</p> </ion-content>
ts頁面
每次重新整理累加10條資料(注意:總資料未必會被10整除,下面的 else if 迴圈就是對該問題的處理)
//總資料 ItemList:any=[]; //頁面預設顯示的資料(該資料為總資料的Top 10) ShowItemList:[]; //重新整理的次數,頁面需要預設顯示10條資料,故為1 PageIndex=1; //每次重新整理載入的資料數 LoadNum=10; //沒有更多資料時顯示 BolNoMoreData:boolean=false; //無限滾動取資料 doInfinite(infiniteScroll) { //當前顯示的資料量 var ShowDataNum = this.PageIndex * this.LoadNum //下拉重新整理後加載的資料量 var EndShowDataNum = (this.PageIndex + 1) * this.LoadNum if (EndShowDataNum<this.ItemList.length){ for(var i = ShowDataNum; i < this.EndShowDataNum; i++){ this.ShowItemList.push(this.ItemList[i]); } }else if( (endShowDataNum-this.ItemList.length)>0 ){ for(var i = ShowDataNum; i < this.ItemList.length; i++){ this.ShowItemList.push(this.ItemList[i]); } }else{ this.BolNoMoreData=true; } this.PageIndex++; infiniteScroll.complete(); }
本來是從資料庫取的資料,但為了更整潔明瞭的顯示 ion-infinite-scroll 的作用,特地去掉了請求服務的程式碼!,本文根據之前從資料庫取值的程式碼改編完成的,純手寫,未經驗證,可能會存在一些錯誤!