vue实现多级表头
Vue 实现多级表头的方法
使用 Element UI 的 el-table 组件
Element UI 的表格组件原生支持多级表头,通过嵌套 el-table-column 实现。

<el-table :data="tableData">
<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 的 a-table 组件
Ant Design Vue 也支持多级表头,通过 columns 配置实现。

const columns = [
{
title: '姓名',
dataIndex: 'name',
key: 'name',
width: 100,
},
{
title: '其他信息',
children: [
{
title: '年龄',
dataIndex: 'age',
key: 'age',
width: 200,
},
{
title: '地址',
children: [
{
title: '街道',
dataIndex: 'street',
key: 'street',
},
{
title: '城市',
dataIndex: 'city',
key: 'city',
},
],
},
],
},
];
自定义实现多级表头
如果没有使用 UI 框架,可以通过嵌套表头的方式实现。
<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 in tableData" :key="item.id">
<td>{{ item.date }}</td>
<td>{{ item.name }}</td>
<td>{{ item.province }}</td>
<td>{{ item.city }}</td>
</tr>
</tbody>
</table>
动态生成多级表头
根据后端返回的数据动态生成多级表头。
function generateColumns(data) {
return data.map(item => {
const column = {
title: item.label,
key: item.key,
};
if (item.children) {
column.children = generateColumns(item.children);
}
return column;
});
}
注意事项
- 多级表头会增加表格的复杂度,可能影响性能
- 表头层级不宜过深,建议控制在3层以内
- 注意表格的响应式设计,确保在小屏幕上也能正常显示
- 表头合并单元格时要注意跨行(rowspan)和跨列(colspan)的正确使用






