项目中遇到这样一个需求:查询到的数据中有一个字段是图片的数组,但是在前段详情页面展示时,要求展示成下面的排版:
每行最多显示3个图片,所以每行都是遍历输出,每个单元格也是遍历输出的,但是数据图片字段是单纯的数组列表,没法做到每三个元素就换行;所以最后,只能改变一下数组内的数据结构了,也就是将一维数组改造成二维数组:
一维数组:[a, b, c, d, e, f, g, ..... ]
二维数组:[[a, b, c], [d, e, f], [g, h, i] ....]
这样子载遍历的话,就可以了;
前端我用的是angular6,遍历起来的话也是很方便的;
首先代码中有着三个变量;
mydiary: any;
size = 3;
imgs: any[] = [];
mydiary对象中的momentAttachmentList字段是图片数组;
size:每行显示的个数;3个不够的话还可以设置多一些;
imgs: 存放图片的新数组
处理方法:
// 格式化图片成九宫格
formartImgs(): void {
if (this.mydiary.momentAttachmentList && this.mydiary.momentAttachmentList.length > 0) {
for (let index = 0; index < this.mydiary.momentAttachmentList.length; index += this.size) {
const element = this.mydiary.momentAttachmentList[index];
this.imgs.push(this.mydiary.momentAttachmentList.slice(index, index + this.size));
}
}
}
前段页面遍历代码:
<ion-grid>
<ion-row *ngFor="let imgsRow of imgs">
<ion-col col-4 col-sm *ngFor="let img of imgsRow">
<img [src]="img.thumbnailPhoto">
</ion-col>
</ion-row>
</ion-grid>