vue实现表格多表头
Vue 实现表格多表头的方法
在 Vue 中实现多表头表格通常可以通过以下两种方式实现:使用第三方组件库(如 Element UI、Ant Design Vue)或手动实现自定义表格组件。
使用 Element UI 实现多表头
Element UI 的 el-table 组件支持多级表头配置,通过嵌套 el-table-column 即可实现。

<el-table :data="tableData" border>
<el-table-column prop="date" label="日期" width="180"></el-table-column>
<el-table-column label="配送信息">
<el-table-column prop="name" label="姓名" width="180"></el-table-column>
<el-table-column label="地址">
<el-table-column prop="province" label="省份" width="120"></el-table-column>
<el-table-column prop="city" label="市区" width="120"></el-table-column>
<el-table-column prop="address" label="详细地址" width="300"></el-table-column>
</el-table-column>
</el-table-column>
</el-table>
使用 Ant Design Vue 实现多表头
Ant Design Vue 的 a-table 组件通过 columns 配置实现多表头。

<template>
<a-table :columns="columns" :data-source="data" bordered />
</template>
<script>
const columns = [
{
title: '姓名',
dataIndex: 'name',
key: 'name',
},
{
title: '其他信息',
children: [
{
title: '年龄',
dataIndex: 'age',
key: 'age',
},
{
title: '地址',
children: [
{
title: '街道',
dataIndex: 'street',
key: 'street',
},
{
title: '小区',
dataIndex: 'building',
key: 'building',
},
],
},
],
},
];
</script>
手动实现自定义多表头表格
如果需要完全自定义实现,可以通过组合 table、thead、tr 和 th 元素手动构建。
<template>
<table class="custom-table">
<thead>
<tr>
<th rowspan="2">日期</th>
<th colspan="3">配送信息</th>
</tr>
<tr>
<th>姓名</th>
<th colspan="2">地址</th>
</tr>
<tr>
<th></th>
<th></th>
<th>省份</th>
<th>市区</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in tableData" :key="index">
<td>{{ item.date }}</td>
<td>{{ item.name }}</td>
<td>{{ item.province }}</td>
<td>{{ item.city }}</td>
</tr>
</tbody>
</table>
</template>
<style>
.custom-table {
border-collapse: collapse;
width: 100%;
}
.custom-table th, .custom-table td {
border: 1px solid #ddd;
padding: 8px;
text-align: center;
}
</style>
动态生成多表头
对于需要动态生成表头的情况,可以通过递归组件实现。
<template>
<table>
<thead>
<tr v-for="(row, rowIndex) in headerRows" :key="'row-' + rowIndex">
<th
v-for="(col, colIndex) in row"
:key="'col-' + colIndex"
:rowspan="col.rowspan"
:colspan="col.colspan"
>
{{ col.title }}
</th>
</tr>
</thead>
<tbody>
<!-- 表格数据行 -->
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
headerRows: [
[
{ title: '日期', rowspan: 2, colspan: 1 },
{ title: '配送信息', rowspan: 1, colspan: 3 }
],
[
{ title: '姓名', rowspan: 1, colspan: 1 },
{ title: '地址', rowspan: 1, colspan: 2 }
]
]
}
}
}
</script>
以上方法可以根据具体需求选择适合的实现方式,第三方组件库提供了更便捷的解决方案,而自定义实现则提供了更大的灵活性。






