给定一个结构,如何生成对应的多级表头的表格?
const fields = [
{
label: "A",
prop: "A"
sub: [
{
label: "A1",
prop: "A1"
},
{
label: "A2",
prop: "A2"
}
]
},
{
label: "B",
prop: "B",
sub: [
{
label: "B1",
prop: "B1"
},
{
label: "B2",
prop: "B2"
}
]
}
]
如果给定的是一个固定层次的嵌套结构,我们可以用两层循环完成。但是当嵌套层次不确定的话,应该怎么递归的生成呢?在vue中该怎么实现?
<script setup lang="ts">
import { ref, version as vueVersion } from 'vue'
import { version as epVersion } from 'element-plus'
import { ElementPlus } from '@element-plus/icons-vue'
const fields = [
{
label: "A",
prop: "A",
sub: [
{
label: "A1",
prop: "A1"
},
{
label: "A2",
prop: "A2"
}
]
},
{
label: "B",
prop: "B",
sub: [
{
label: "B1",
prop: "B1"
},
{
label: "B2",
prop: "B2"
}
]
}
]
const tableData = [
{ A1: "peter", "A2": "huan", B1: "tom", B2: "li" },
{ A1: "peter", "A2": "huan", B1: "tom", B2: "li" },
{ A1: "peter", "A2": "huan", B1: "tom", B2: "li" },
{ A1: "peter", "A2": "huan", B1: "tom", B2: "li" },
]
</script>
<template>
<el-table :data="tableData">
<el-table-column v-for="item in fields" :prop="item.prop" :label="item.label">
<template v-if="item.sub">
<el-table-column v-for="subItem in item.sub" :prop="subItem.prop" :label="subItem.label" >
</el-table-column>
</template>
</el-table-column>
</el-table>
</template>
把你的el-table-column逻辑封装为一个组件,组件内判断有没有sub,有的话递归调用自己