根据相同参数【例如id】进行合并单元格
1.多级纵向表头示意图
l
2. 步骤
树形表头数据转成一维数组
判断id相同的个数,并将相同id的行数添加到相同id的项内;[id个数不等于1]
3.代码
<template>
<el-table :show-header="false" :data="tableData" row-key="id" border scrollbar-always-on :span-method="SpanMethod"
:header-cell-style="{
'text-align': 'center',
color: '#333'
}">
<el-table-column align="center" prop="asd" width="180" />
<el-table-column align="center" prop="answer" />
</el-table>
</template>
<script setup>
import { ref } from 'vue'
const tableData = ref([])//原始表头数据
const SpanMethod = (row) => {
/**
* 合并行 计算方法
* 1、判断是否有row.row.rowspan参数,
* row.row.rowspan:row.row.rowspan相同id的个数且相同id的个数>1
* 2.列索引为0时,展示列数组中查找 row.row.id所在的索引,进行条件判断【row.row.rowspan > 1且 index11 !== -1】
* 3.满足条件rowspan等于row.row.rowspan;不满足rowspan: 0,colspan: 0,
* */
if (row.columnIndex === 0) {
const index11 = tableData.value.findIndex(
(item11) => item11.id === row.row.id
)
if (row.row.rowspan && row.row.rowspan > 1 && index11 !== -1) {
if (row.rowIndex == index11) {
return {
rowspan: row.row.rowspan,
colspan: 1,
}
} else {
return {
rowspan: 0,
colspan: 0,
}
}
}
}
if (!row.row.rowspan) {
return {
rowspan: 1,
colspan: 1,
}
}
}
//判断id相同的个数,并将相同id的行数添加到相同id的项内;[id个数不等于1]
function getSpanArr(list) {
//查找数组中相同id的个数,并存放到rowspan,添加到相同id项内
let groups = list.reduce((groups, item) => {
if (!groups[item.id]) {
groups[item.id] = [];
}
groups[item.id].push(item);
return groups;
}, {});
let result = [];
for (let id in groups) {
let group = groups[id];
if (group.length === 1) {
result.push({ ...group[0] }); // 直接添加原始对象,不添加rowspan属性
} else {
let rowspan = group.length;
for (let i = 0; i < group.length; i++) {
result.push({
...group[i],
rowspan: group.length // 添加rowspan属性,并设置其值为组内元素数量
});
}
}
}
tableData.value = result
console.log(tableData.value, "tableData.value ")
}
getSpanArr(tableData.value)
//表头数据
tableData.value = [
{
"id": 120,
"asd": "天气",
"asdList": null
},
{
"id": 121,
"asd": "日期",
"asdList": null
},
{
"id": 127,
"asd": "地区",
"asdList": [
{
"id": 686,
"asd": "(1)北京",
"asdList": null
},
{
"id": 687,
"asd": "(2)上海",
"asdList": null
},
{
"id": 688,
"asd": "(3)南京",
"asdList": null
},
{
"id": 689,
"asd": "(4)广州",
"asdList": null
},
]
},
{
"id": 128,
"asd": "资源",
"asdList": null
},
{
"id": 129,
"asd": "区域",
"asdList": [
{
"id": 346,
"asd": "区域1",
"asdList": null
},
{
"id": 347,
"asd": "区域2",
"asdList": null
},
{
"id": 348,
"asd": "区域3",
"asdList": null
},
{
"id": 349,
"asd": "区域4",
"asdList": null
},
]
}
]
//树形数据转为一维数组
let cc = tableData.value.flatMap((item) => {
if (item.asdList) {
return item.asdList.map((child) => ({
...child,
asd: item.asd + '-' + child.asd,
id: item.id,
aswerId: child.id,
title: item.asd,
answer: child.asd,
}));
} else {
return { ...item, aswerId: item.id };
}
});
tableData.value = cc
console.log(tableData.value)
</script>
4.打印数据展示
(1)树形数据转为一维数组后,tableData.value的值