element ui 实现表格多级表头动态渲染
一 效果图
二 封装俩个组件,分别为DynamicTable.vue 跟TableColumn.vue TableColumn.vue 使用递归方法,对表头进行循环生成
DynamicTable.vue
<template> <el-table :data="tableData"> <template v-for="item in tableHeader"> <table-column v-if="item.children && item.children.length" :key="item.id" :coloumn-header="item" ></table-column> <el-table-column v-else :key="item.id" :label="item.label" :prop="item.prop" ></el-table-column> </template> </el-table> </template> <script> import TableColumn from "./TableColumn"; export default { props: { // 表格的数据 tableData: { type: Array, required: true, }, // 多级表头的数据 tableHeader: { type: Array, required: true, }, }, components: { TableColumn, }, }; </script> <style scoped> </style>
TableColumn.vue
<template> <el-table-column :label="coloumnHeader.label" :prop="coloumnHeader.label"> <template v-for="item in coloumnHeader.children"> <tableColumn v-if="item.children && item.children.length" :key="item.id" :coloumn-header="item" ></tableColumn> <el-table-column v-else :key="item.name" :label="item.label" :prop="item.prop" ></el-table-column> </template> </el-table-column> </template> <script> export default { name: "tableColumn", props: { coloumnHeader: { type: Object, required: true, }, }, }; </script> <style scoped> </style>
三 调用组件
<template>
<div>
<dynamic-table
:table-data="tableData"
:table-header="tableConfig"
></dynamic-table>
</div>
</template>
<script>
import DynamicTable from "@/components/DynamicTable";
export default {
components: {
DynamicTable,
},
data() {
return {
// 表数据
tableData: [
{
date: "2021-09-06",
name: "张三",
phone: "15739951445",
province: "河北省",
city: "张家口",
address: "河北省张家口市桥西区",
},
],
// 表头数据
tableConfig: [
{
id: 100,
label: "日期",
prop: "date",
},
{
id: 200,
label: "配送信息",
prop: "",
children: [
{
id: 210,
label: "姓名",
prop: "name",
},
{
id: 220,
label: "电话",
prop: "phone",
},
{
id: 200,
label: "地址",
prop: "",
children: [
{
id: 210,
label: "省份",
prop: "province",
},
{
id: 220,
label: "城市",
prop: "city",
},
{
id: 220,
label: "详细地址",
prop: "address",
},
],
},
],
},
],
};
},
};
</script>
<style scoped>
</style>

浙公网安备 33010602011771号