表格动态合并,序号连续
效果:
<el-table :data="tableData" style="width: 100%" v-loading="tableDataLoading" :header-cell-style="{ background: '#FAFAFA' }" :span-method="objectSpanMethod" > <el-table-column prop="mergeKey" label="序号" width="80"> <template slot-scope="scope"> <span>{{ scope.row.mergeKey + 1 }}</span> </template> </el-table-column> </el-table>
import { resoveData, filterTable, trainMerge, } from "@/utils/util.js";
methods: { objectSpanMethod({ row, column, rowIndex, columnIndex }) { if ([0, 1, 2, 12, 13, 14].includes(columnIndex)) { let _row = this.rowspan[rowIndex]; // 合并的行 let _col = this.rowspan[rowIndex] > 0 ? 1 : 0; // 1是开头0是被合并 return [_row, _col]; } }, getList() { this.tableDataLoading = true; let params = { pageNum: this.listQuery.pageNum, pageSize: this.listQuery.pageSize, ...this.listQuery, // 参数 }; continuousRecordsPage(params).then((res) => { this.tableData = res.data.records; let newData = resoveData(res.data.records, "filingInfos"); this.tableData = filterTable(newData); console.log(this.tableData); this.rowspan = trainMerge(newData, "mergeKey"); // 获取相同类型合并列的数据 console.log(this.rowspan); this.total = res.data.total; this.tableDataLoading = false; }); }, }
util.js // 把数据合并了进行拆解arr=>后台数据;arrKey=>合并数据的key export function resoveData(arr, arrKey, mergeKey = "mergeKey") { let newData = []; arr.forEach((item, index) => { // newData.push(item); item[arrKey].forEach(el => { newData.push({ ...el, ...item, [mergeKey]: index, }) }) }) return newData } // 格式化表格null的数据为 - export function filterTable(data) { if (!data) return []; data.forEach(item => { for (let key in item) { if (item[key] == null || item[key] === '') item[key] = '-'; } }) return data; } // 传入element表格需要合并相同列的key返回合并行组成的Array export function trainMerge(arr, key) { let rowspan = []; var obj = {}, k; for (var i = 0, len = arr.length; i < len; i++) { k = arr[i][key]; //需要合并的字段 if (obj[k]) obj[k]++; else obj[k] = 1; } console.log('===', obj); //保存结果{el-'元素',count-出现次数} for (var o in obj) { for (let i = 0; i < obj[o]; i++) { if (i === 0) { rowspan.push(obj[o]); } else { rowspan.push(0); } } } return rowspan; }