vue 实现tab表格
Vue 实现 Tab 表格
基础结构设计
使用 Vue 的 v-for 动态生成 Tab 标题,配合 v-show 或 v-if 控制表格内容的显示切换。以下为示例代码框架:
<template>
<div>
<div class="tabs">
<button
v-for="(tab, index) in tabs"
:key="index"
@click="activeTab = index"
:class="{ 'active': activeTab === index }"
>
{{ tab.title }}
</button>
</div>
<div class="tab-content">
<table v-for="(tab, index) in tabs" :key="index" v-show="activeTab === index">
<thead>
<tr>
<th v-for="(header, i) in tab.headers" :key="i">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, rowIndex) in tab.data" :key="rowIndex">
<td v-for="(cell, cellIndex) in row" :key="cellIndex">{{ cell }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
数据绑定
在 Vue 实例的 data 中定义动态数据:
<script>
export default {
data() {
return {
activeTab: 0,
tabs: [
{
title: '表格1',
headers: ['姓名', '年龄'],
data: [
['张三', 25],
['李四', 30]
]
},
{
title: '表格2',
headers: ['产品', '价格'],
data: [
['手机', 2999],
['电脑', 5999]
]
}
]
}
}
}
</script>
样式优化
通过 CSS 增强交互视觉效果:
<style scoped>
.tabs button {
padding: 8px 16px;
margin-right: 5px;
border: none;
cursor: pointer;
}
.tabs button.active {
background-color: #42b983;
color: white;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
}
</style>
动态数据加载
如需从接口异步加载数据,可在 mounted 或方法中处理:
methods: {
async fetchData() {
const response = await axios.get('/api/tab-data');
this.tabs = response.data;
}
},
mounted() {
this.fetchData();
}
组件化拆分
对于复杂场景,可将 Tab 和 Table 拆分为独立组件:

<template>
<tab-container :tabs="tabs">
<tab-content v-for="(tab, index) in tabs" :key="index">
<data-table :headers="tab.headers" :rows="tab.data" />
</tab-content>
</tab-container>
</template>






