2018在ionic项目中用到的组件有不少,这篇文章讲一讲ion-reorder-group这个组件的使用。刚开始我都不知道ionic4中已经封装了拖拽排序的组件,也是主管告诉个人。使用了这个组件的经历告诉我:仔细读官方文档,是没错的!
HTML中使用组件,代码以下ionic
<!--一个排序组合一个ion-reorder-group--> <ion-reorder-group [disabled]="false" (ionItemReorder)="reorder($event)"> <ion-item color="tertiary" *ngFor="let field of fieldList,let i=index"> <ion-label>{{ field.name}}</ion-label> <!--拖拽按钮--> <ion-reorder slot="end"></ion-reorder> </ion-item> </ion-reorder-group>
ionItemReorder绑定reorder事件,是item被拖拽时会被触发的事件,这个事件是ionic绑定在IonReorderGroup组件上的。记得必定要设置disabled属性,否则不会有拖拽按钮出现。this
reorder(ev) { try { if (ev.detail.to === this.fieldList.length) { ev.detail.to -= 1; } if (ev.detail.from < ev.detail.to) { this.fieldList.splice(ev.detail.to + 1, 0, this.fieldList[ev.detail.from]); this.fieldList.splice(ev.detail.from, 1); } if (ev.detail.from > ev.detail.to) { this.fieldList.splice(ev.detail.to, 0, this.fieldList[ev.detail.from]); this.fieldList.splice(ev.detail.from + 1, 1); } ev.detail.complete(); } catch (e) { return; } }
customEvent继承自Event,添加了detail属性,包含from,to,complete,分别记录拖拽条目的先后index,complete方法需在拖拽结束后调用,不然会卡住。spa