vue+实现table切换
Vue 实现表格切换功能
在Vue中实现表格切换功能通常涉及动态渲染不同的表格数据或切换表格的显示状态。以下是几种常见实现方式:
数据驱动表格切换
通过改变数据源实现表格内容切换:
<template>
<div>
<button @click="currentTable = 'table1'">表格1</button>
<button @click="currentTable = 'table2'">表格2</button>
<table v-if="currentTable === 'table1'">
<tr v-for="item in table1Data" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
<table v-if="currentTable === 'table2'">
<tr v-for="item in table2Data" :key="item.id">
<td>{{ item.value }}</td>
</tr>
</table>
</div>
</template>
<script>
export default {
data() {
return {
currentTable: 'table1',
table1Data: [{id: 1, name: 'A'}, {id: 2, name: 'B'}],
table2Data: [{id: 1, value: 100}, {id: 2, value: 200}]
}
}
}
</script>
组件化表格切换
将不同表格封装为组件,通过动态组件切换:
<template>
<div>
<button @click="currentComponent = 'TableA'">表格A</button>
<button @click="currentComponent = 'TableB'">表格B</button>
<component :is="currentComponent"></component>
</div>
</template>
<script>
import TableA from './TableA.vue'
import TableB from './TableB.vue'
export default {
components: { TableA, TableB },
data() {
return {
currentComponent: 'TableA'
}
}
}
</script>
使用v-show优化性能
如果需要频繁切换且保持DOM状态,可以使用v-show替代v-if:
<table v-show="showTable1">
<!-- 表格内容 -->
</table>
<table v-show="!showTable1">
<!-- 表格内容 -->
</table>
选项卡式表格切换
结合CSS实现选项卡样式:
<template>
<div class="tab-container">
<div class="tab-header">
<div
v-for="tab in tabs"
:key="tab.id"
@click="activeTab = tab.id"
:class="{ active: activeTab === tab.id }"
>
{{ tab.title }}
</div>
</div>
<div class="tab-content">
<table v-if="activeTab === 1">
<!-- 表格1内容 -->
</table>
<table v-if="activeTab === 2">
<!-- 表格2内容 -->
</table>
</div>
</div>
</template>
<style>
.tab-header div {
display: inline-block;
padding: 10px;
cursor: pointer;
}
.tab-header div.active {
border-bottom: 2px solid blue;
}
</style>
使用第三方组件库
对于更复杂的表格需求,可以考虑使用Element UI、Ant Design Vue等UI库:
<template>
<el-tabs v-model="activeName">
<el-tab-pane label="表格1" name="first">
<el-table :data="tableData1"></el-table>
</el-tab-pane>
<el-tab-pane label="表格2" name="second">
<el-table :data="tableData2"></el-table>
</el-tab-pane>
</el-tabs>
</template>
以上方法可根据具体需求选择使用,数据驱动方式适合简单场景,组件化方式更适合复杂表格,第三方库则提供开箱即用的解决方案。







