根据树形结构数据生成table表格,支持合并表格。
<template>
<div>
<table border="1">
<thead>
<tr>
<!-- 循环渲染表头 -->
<th v-for="header in th" :key="header">{{ header }}</th>
</tr>
</thead>
<tbody>
<!-- 循环渲染列表数据 -->
<template v-for="(item, index) in list">
<tr :key="index">
<!-- 第一列,根据子项数量确定 rowspan -->
<td :rowspan="getRowSpan(item)">{{ item.label }}</td>
<!-- 第二列,如果没有子项则显示 sum -->
<td v-if="!item.children">{{ item.sum }}</td>
</tr>
<template v-if="item.children">
<template v-for="(child, childIndex) in item.children">
<tr v-if="!child.children" :key="childIndex">
<!-- 子项的第一列和第二列 -->
<td>{{ child.label }}</td>
<td>-</td>
<td>{{ child.sum }}</td>
</tr>
<tr v-else>
<!-- 子项有孙子项时只显示第一列,并设置 rowspan -->
<td :rowspan="getRowSpan(child)">{{ child.label }}</td>
</tr>
<template v-if="child.children">
<template v-for="(grandChild, grandChildIndex) in child.children">
<tr :key="'gc-' + grandChildIndex">
<!-- 孙子项的第一列和第二列 -->
<td>{{ grandChild.label }}</td>
<td>{{ grandChild.sum }}</td>
</tr>
</template>
</template>
</template>
</template>
</template>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
// 表头数据
th: ["客户来源", "测试数量数"],
// 主要数据列表
list: [
{
label: "用户录入",
sum: 266,
children: [
{ label: "未出现", sum: 136 },
{
label: "已清理", sum: 0, children: [
{ label: "互联网", sum: 0 },
{ label: "局域网", sum: 1 }
]
},
{ label: "无需核实", sum: 130 }
]
},
{
label: "流量发现",
sum: 496,
children: [
{ label: "已核实", sum: 337 },
{
label: "已忽略",
sum: 1,
children: [
{ label: "互联网", sum: 0 },
{ label: "局域网", sum: 1 }
]
},
{
label: "新出现",
sum: 158,
children: [
{ label: "互联网", sum: 127 },
{ label: "局域网", sum: 31 }
]
}
]
}
]
};
},
methods: {
// 递归计算 rowspan 的值
getRowSpan(item) {
let count = 1;
if (item.children) {
for (let child of item.children) {
count += this.getRowSpan(child);
}
}
return count;
}
}
};
</script>