element-ui使用表格组件,实现表格、子表格带children的数据单元格合并,当名称相同时合并名称和其他列,并且有些列不合并
示例图

代码实现
<el-table
:data="tableData"
:span-method="objectSpanMethod"
border
row-key="id"
default-expand-all
:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
>
<template v-for="(item, ind) of thead">
<el-table-column
:key="ind"
:prop="item.field"
:label="item.title"
:width="item.width"
>
</el-table-column>
</template>
</el-table>
data() {
return {
date: "2022-12",
rowArr: [],
thead:[
{
title: "序号",
field: "sort",
width: "70",
align: "center",
},
{
title: "单位名称",
field: "unitName",
align: "center",
},
{
title: "产量名称",
align: "center",
field: "yieldName",
},
{
title: "本月数",
align: "center",
field: "numberOfMonths",
},
{
title: "本期累计",
align: "center",
field: "fiscalYear",
},
],
tableData: [
{
id: "1",
sort: "1",
unitName: "名称1",
yieldName: "产量1",
numberOfMonths: "2",
fiscalYear: "20255",
},
{
id: "2",
sort: "2",
unitName: "名称1",
yieldName: "产量2",
numberOfMonths: "2",
fiscalYear: "20255",
},
{
id: "3",
sort: "3",
unitName: "名称3",
yieldName: "产量3",
numberOfMonths: "3",
fiscalYear: "20255",
children: [
{
id: "4",
sort: null,
unitName: "名称3",
yieldName: "产量3-1",
numberOfMonths: "4",
fiscalYear: "20255",
},
{
id: "5",
sort: null,
unitName: "名称5",
yieldName: "产量3-2",
numberOfMonths: "555",
fiscalYear: "2025885",
},
{
id: "6",
sort: null,
unitName: "名称5",
yieldName: "产量3-3",
numberOfMonths: "555",
fiscalYear: "2025885",
},
],
},
{
id: "7",
sort: "4",
unitName: "名称7",
yieldName: "产量7",
numberOfMonths: "7",
fiscalYear: "20255",
children: [
{
id: "8",
sort: null,
unitName: "名称8",
yieldName: "产量7-1",
numberOfMonths: "8",
fiscalYear: "20255",
},
{
id: "9",
sort: null,
unitName: "名称8",
yieldName: "产量7-2",
numberOfMonths: "8",
fiscalYear: "20255",
},
],
},
],
};
},
mounted() {
this.rowArr = $.getRow(this.tableData, "unitName");
},
methods: {
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
const noMergeColumns = ["yieldName"];
if (noMergeColumns.includes(column.property)) {
return [1, 1];
}
if (columnIndex > 0) {
let arr = this.rowArr;
if (arr[rowIndex] > 0) {
return [arr[rowIndex], 1];
} else {
return [0, 0];
}
}
return [1, 1];
},
getRow(data, type) => {
let spanArr = [];
let pos = 0;
let childrenCount = 0;
data.forEach((item, index) => {
if (index === 0) {
spanArr.push(1);
pos = 0;
} else {
if (data[index][type] === data[index - 1][type]) {
spanArr[pos + childrenCount] += 1;
spanArr.push(0);
} else {
spanArr.push(1);
pos = index;
}
}
if (item.children) {
childrenCount += item.children.length;
spanArr = spanArr.concat(getRow(item.children, "unitName"));
}
});
return spanArr;
},
},