一 效果圖
二 封裝倆個組件,分別為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>
