因为工作需要,需要一个如上图(不确定层级的)多层级表头的表格,搜索网上的方法,多为vue2+element-ui的方法,查到的vue3+Element-plus的方法仅为建立两层级表格,经借鉴大神方法并修改成功,供自己留存,大神略过。
一、创建动态表格组件 DynamicTable.vue
代码如下:
<template>
<el-table
:data="tableData"
:height="tableHeight"
style="width: 100%"
size="small"
>
<template v-for="item in tableHeader">
<MyTableColumn
v-if="item.children && item.children.length"
:coloumnHeader="item"
></MyTableColumn>
<el-table-column
v-else
:label="item.label"
:prop="item.prop"
:sortable="item.sort"
header-align="center"
:align="item.align"
:width="item.width"
></el-table-column>
</template>
</el-table>
</template>
<script setup lang="ts">
import MyTableColumn from "./MyTableColumn.vue";
//其中 tableHeight 是为了控制表格高度,非必需
const props = defineProps(["tableData", "tableHeader", "tableHeight"]);
</script>
<style scoped lang="scss"></style>
二,创建表格列的组件 MyTableColumn.vue
代码如下,通过调用组件自身的方法,递归循环。
<template>
<el-table-column :label="coloumnHeader.label" header-align="center">
<template v-for="item in coloumnHeader.children">
<MyTableColumn
v-if="item.children && item.children.length"
:coloumnHeader="item"
></MyTableColumn>
<el-table-column
v-else
:label="item.label"
:prop="item.prop"
:sortable="item.sort"
header-align="center"
:align="item.align"
:width="item.width"
></el-table-column>
</template>
</el-table-column>
</template>
<script setup lang="ts">
const props = defineProps(["coloumnHeader"]);
</script>
<style scoped lang="scss"></style>
三、使用动态表格组件
<template>
<DynamicTable
ref="dataTableRef"
:style="{ height: tableHeight + 'px' }"
:tableHeight="tableHeight"
:tableData="tableData"
:tableHeader="tableHeader"
></DynamicTable>
</template>
<script setup lang="ts">
import DynamicTable from "@/components/DynamicTable.vue";
import { ref, reactive, onMounted, nextTick} from "vue";
//表格的高度
const tableHeight = ref(0);
// 静态表格表头及数据
const tableHeader = reactive([
{
label: "基本信息",
children: [
{
label: "姓名",
children: [
{
label: "姓名1",
prop: "name",
align: "center",
},
{
label: "姓名2",
prop: "namet",
align: "center",
},
],
},
{
label: "生日",
sort: true,
prop: "birth",
align: "center",
},
],
},
{ label: "地址", sort: false, prop: "address", align: "left" },
{
label: "年龄",
sort: true,
prop: "age",
},
{
label: "电话",
sort: false,
prop: "phone",
},
]);
const tableData = reactive([
{
name: "张三",
namet: "张三2",
address: "广西南宁市贤宾路1号",
birth: "2021-01-01",
age: 20,
phone: "13877100000",
},
{
name: "李四",
namet: "李四2",
birth: "2022-01-01",
address: "广西南宁市悦宾路1号",
age: 19,
phone: "13077700000",
},
]);
onMounted(() => {
nextTick(() => {
tableHeight.value = window.innerHeight - (51 + 30 + 1) + 3 - 154;
});
});
</script>
<style scoped lang="scss">
</style>
至此,该功能完成,加载后端数据可实现多层级(理论上无限级)表头的动态创建。
本文参考了 https://www.cnblogs.com/caohuiyuan/p/15246265.html 的内容,特向原作者致谢。
版权声明:本文为nnslyx原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。