vue实现多级表头
Vue 实现多级表头的方法
使用 Element UI 的表格组件
Element UI 的 el-table 组件支持多级表头,通过嵌套 el-table-column 实现。以下是一个示例代码:

<template>
<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="180"></el-table-column>
<el-table-column prop="city" label="市区" width="180"></el-table-column>
<el-table-column prop="address" label="地址" width="300"></el-table-column>
</el-table-column>
</el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{
date: '2016-05-03',
name: '王小虎',
province: '上海',
city: '普陀区',
address: '上海市普陀区金沙江路 1518 弄'
}
]
}
}
}
</script>
使用 Ant Design Vue 的表格组件
Ant Design Vue 的 a-table 组件也支持多级表头,通过 columns 配置实现。示例代码如下:

<template>
<a-table :columns="columns" :data-source="data" bordered />
</template>
<script>
export default {
data() {
return {
columns: [
{
title: '姓名',
dataIndex: 'name',
key: 'name'
},
{
title: '其他信息',
children: [
{
title: '年龄',
dataIndex: 'age',
key: 'age'
},
{
title: '地址',
children: [
{
title: '街道',
dataIndex: 'street',
key: 'street'
},
{
title: '城市',
dataIndex: 'city',
key: 'city'
}
]
}
]
}
],
data: [
{
key: '1',
name: 'John Brown',
age: 32,
street: 'Lake Park',
city: 'New York'
}
]
}
}
}
</script>
自定义实现多级表头
如果需要自定义实现多级表头,可以通过组合 HTML 和 CSS 实现。以下是一个简单的示例:
<template>
<table class="multi-header-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>
<td>2016-05-03</td>
<td>王小虎</td>
<td>上海</td>
<td>普陀区</td>
</tr>
</tbody>
</table>
</template>
<style>
.multi-header-table {
border-collapse: collapse;
width: 100%;
}
.multi-header-table th, .multi-header-table td {
border: 1px solid #ddd;
padding: 8px;
text-align: center;
}
</style>
动态生成多级表头
对于动态数据,可以通过递归组件实现多级表头。以下是一个递归组件的示例:
<template>
<table>
<thead>
<tr>
<th v-for="col in columns" :key="col.key" :colspan="col.children ? col.children.length : 1">
{{ col.title }}
</th>
</tr>
<template v-if="hasChildren">
<tr>
<template v-for="col in columns">
<template v-if="col.children">
<multi-header :columns="col.children" :key="col.key"></multi-header>
</template>
</template>
</tr>
</template>
</thead>
</table>
</template>
<script>
export default {
name: 'MultiHeader',
props: {
columns: Array
},
computed: {
hasChildren() {
return this.columns.some(col => col.children)
}
}
}
</script>
通过以上方法,可以在 Vue 中灵活实现多级表头的需求。






