var newArr = [];
listData.forEach(function(item, i) {
var index = -1;
var isExists = newArr.some(function(newItem, j) {
if (item.month === newItem.month) {
index = j;
return true;
}
});
if (!isExists) {
newArr.push({
month: item.month,
child: [item]
});
} else {
newArr[index].child.push(item);
}
});
接口返回数据若有分页,则需待数组数据加载push完后,再调用分组方法。(uniapp 代码为例)
<template>
<view class="w-100" v-for="(item,index) in listData" :key="index">
<view class="log-month"> {{item.month}} </view>
<view class="log-child" v-for="(ele,idx) in item.child" :key="idx">
<view class="log-child_item">
<view class="w-100 text-cut"> {{ele.desc}} </view>
<view class="w-100 text-xs text-gray4 mt10"> {{parseTime(ele.reg_date, '{y}-{m}-{d}')}}
</view>
</view>
<view class="cus-flex-end-j text-xxl" style="width: 140;"
:style="(ele.score).indexOf('+') !=-1?'color: #FF4E76;':'color: #121212;'">
{{ele.score}}
</view>
</view>
</view>
</template>
<script>
import api from "@/utils/api.js";
export default {
data() {
return {
pageNum: 1,
pageTotal: 0,
httpList: [],
listData: [],
}
},
created() {
this.resetData();
},
onPullDownRefresh() {
this.resetData()
setTimeout(() => {
uni.stopPullDownRefresh()
}, 300)
},
onReachBottom() {
if (this.httpList.length == this.pageTotal) {
uni.showToast({
title: '已经到底了',
icon: 'none'
})
return
} else {
uni.showToast({
title: '正在加载中',
icon: 'none'
})
this.pageNum = this.pageNum + 1;
this.finalFormattedArray();
}
},
methods: {
resetData() {
this.pageNum = 1;
this.pageTotal = 0;
this.httpList = [];
this.finalFormattedArray();
},
finalFormattedArray() {
// 等getList 接口执行完之后,运行分组分类方法
this.getList(() => {
this.dataResort();
});
},
getList(callback) {
api.接口名({
data: {
pageNum: this.pageNum,
pageSize: 10
}
}).then(res => {
/* 数据格式为:
{
day: "2024-07-16",
desc: "测试",
id: "f14490",
month: "2024-07",
reg_date: "2024-07-16 09:12:34",
score: "+2",
type: "0",
}
*/
this.pageTotal = res.data.total;
if (res.data.total != '' && res.data.total > 0) {
if (this.httpList.length < res.data.total) {
res.data.list.map(item => {
this.httpList.push(item);
});
callback();
}
};
});
},
dataResort() {
var arr = JSON.parse(JSON.stringify(this.httpList))
var newArr = [];
arr.forEach(function(item, i) {
var index = -1;
var isExists = newArr.some(function(newItem, j) {
if (item.month === newItem.month) {
index = j;
return true;
}
});
if (!isExists) {
newArr.push({
month: item.month,
child: [item]
});
} else {
newArr[index].child.push(item);
}
});
this.listData = newArr;
},
}
}
</script>
<style lang="scss">
.log-month {
width: calc(100% - 60rpx);
padding: 30rpx 30rpx 20rpx;
margin-top: 10rpx;
}
.log-child {
width: calc(100% - 80rpx);
padding: 20rpx 40rpx;
display: flex;
align-items: center;
justify-content: space-between;
background: #FCFCFC;
box-shadow: 0rpx 2rpx 12rpx 0rpx rgba(14, 8, 77, 0.04);
&_item {
width: calc(100% - 160rpx);
flex-direction: column;
display: flex;
align-items: flex-start;
justify-content: center;
}
}
</style>