效果图:
需求:配置优惠活动优惠券包,一个活动可以配置一张或者多张优惠券
数据支持:
{
"id": 9, //活动id
...,
"coupon_pack": [
{
"id": 19, //券包的id
"coupon_id": 9,
...
},
{
"id": 20, //券包的id
"coupon_id": 9,
...
}
],
},
代码实现:
1.调用接扣获取数据 将二维数组降维成一维数组
//降维的方法
const showList = (list: any[]) => {
const mergeList = ref<any[]>([]) //合并后的列表
let newItem = {} as any
list.forEach(item => {
item.coupon_pack.map(pack => {
pack.child_id = pack.id
const { id, ...rest } = pack
return rest
}).forEach(pack => {
newItem = {
...item,
...pack
}
mergeList.value.push(newItem)
})
})
return mergeList.value
}
//从后端获取数据
const couponList = ref<ICouponListResponse[]>([])
const getCouponList = async () => {
const res = await reqxxxxx(page.value, pageSize.value, params) //调用接口
if (res.code !== 0) {
return ElMessage.error(res.message)
}
total.value = res.data.total
couponList.value = res.data.data
couponList.value = await showList(couponList.value) //转换成一维数组
getMergeRow(couponList.value) //合并前的准备
}
2. 获取需要合并的行和开始合并的位置,完成合并
const getMergeRow = (list: any[]) => {
for (var i = 0; i < list.length; i++) {
if (i === 0) {
mergeRowCount.value.push(1) //第一个数据 默认合并1行
mergePosition.value = 0 //开始位置下标默认为0
} else {
// 相同id进行合并
if (list[i].id === list[i - 1].id) {
mergeRowCount.value[mergePosition.value] += 1;
mergeRowCount.value.push(0);
} else {
mergeRowCount.value.push(1);
mergePosition.value = i;
}
}
}
}
interface SpanMethodProps {
row: ICouponListResponse
column: TableColumnCtx<ICouponListResponse>
rowIndex: number
columnIndex: number
}
const spanMethod = ({ row, column, rowIndex, columnIndex }: SpanMethodProps) => {
//合并前两列
if (columnIndex === 0) {
const _row = mergeRowCount.value[rowIndex];
const _col = _row > 0 ? 1 : 0;
return {
rowspan: _row,
colspan: _col
}
}
if (columnIndex === 1) {
const _row = mergeRowCount.value[rowIndex];
const _col = _row > 0 ? 1 : 0;
return {
rowspan: _row,
colspan: _col
}
}
}
html:
<el-table :span-method="spanMethod"> ...