在做表格展示时,通常会遇到合并相同日期/id行的需求;
<template><div><el-table:data="tableData":span-method="objectSpanMethod"borderstyle="width: 100%; margin-top: 20px"><el-table-column prop="id" label="ID" width="180" /><el-table-column prop="name" label="Name" /><el-table-column prop="amount1" label="Amount 1" /><el-table-column prop="amount2" label="Amount 2" /><el-table-column prop="amount3" label="Amount 3" /></el-table></div>
</template><script lang="ts" setup>
import type { TableColumnCtx } from "element-plus";const tableData: User[] = [{id: "12987122",name: "Tom",amount1: "234",amount2: "3.2",amount3: 10,},{id: "12987122",name: "Tom",amount1: "234",amount2: "3.2",amount3: 10,},{id: "12987124",name: "Tom",amount1: "324",amount2: "1.9",amount3: 9,},{id: "12987125",name: "Tom",amount1: "621",amount2: "2.2",amount3: 17,},{id: "12987126",name: "Tom",amount1: "539",amount2: "4.1",amount3: 15,},{id: "12987123",name: "Tom2",amount1: "1565",amount2: "4.4453",amount3: 124,},{id: "12987123",name: "Tom3",amount1: "16523",amount2: "4.433",amount3: 123,},{id: "12987123",name: "Tom",amount1: "165",amount2: "4.43",amount3: 12,},
];
interface User {id: string;name: string;amount1: string;amount2: string;amount3: number;
}interface SpanMethodProps {row: User;column: TableColumnCtx<User>;rowIndex: number;columnIndex: number;
}const handleTableData = (tableData: any) => {let rowSpanArr: any = [],position = 0;tableData.forEach((item: any, index: number) => {if (index == 0) {rowSpanArr.push(1);position = 0;} else {if (item.id == tableData[index - 1].id) {rowSpanArr[position] += 1; //id相同,数组中的某一项值+1rowSpanArr.push(0); // 被合并的行,push 0 占位} else {rowSpanArr.push(1);position = index;}}});return rowSpanArr;
};const objectSpanMethod = ({row,column,rowIndex,columnIndex,
}: SpanMethodProps) => {let rowSpanArr = handleTableData(tableData);if (columnIndex === 0) {const rowSpan = rowSpanArr[rowIndex];return {rowspan: rowSpan, //行colspan: 1, //列};}
};
</script>