vue 实现table切换
实现 Vue 表格切换功能
在 Vue 中实现表格切换功能通常涉及动态渲染不同的表格数据或切换不同的表格样式。以下是几种常见的实现方式:
动态数据切换
通过改变表格绑定的数据源实现切换:
<template>
<div>
<button @click="currentTable = 'table1'">表格1</button>
<button @click="currentTable = 'table2'">表格2</button>
<table>
<thead>
<tr>
<th v-for="col in columns" :key="col">{{ col }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in activeData" :key="row.id">
<td v-for="col in columns" :key="col">{{ row[col] }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
currentTable: 'table1',
table1Data: [...],
table2Data: [...],
columns: ['id', 'name', 'age']
}
},
computed: {
activeData() {
return this.currentTable === 'table1' ? this.table1Data : this.table2Data
}
}
}
</script>
组件切换方式
使用动态组件切换不同的表格组件:
<template>
<div>
<button @click="currentComponent = 'TableA'">表格A</button>
<button @click="currentComponent = 'TableB'">表格B</button>
<component :is="currentComponent" :data="tableData"/>
</div>
</template>
<script>
import TableA from './TableA.vue'
import TableB from './TableB.vue'
export default {
components: { TableA, TableB },
data() {
return {
currentComponent: 'TableA',
tableData: [...]
}
}
}
</script>
条件渲染
使用 v-if/v-show 控制不同表格的显示:
<template>
<div>
<button @click="showTable1 = true; showTable2 = false">表格1</button>
<button @click="showTable1 = false; showTable2 = true">表格2</button>
<table v-if="showTable1">
<!-- 表格1内容 -->
</table>
<table v-if="showTable2">
<!-- 表格2内容 -->
</table>
</div>
</template>
使用第三方表格组件
结合 Element UI 或 Ant Design Vue 等 UI 库实现:
<template>
<div>
<el-radio-group v-model="currentTable">
<el-radio-button label="table1">表格1</el-radio-button>
<el-radio-button label="table2">表格2</el-radio-button>
</el-radio-group>
<el-table :data="activeData">
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
</el-table>
</div>
</template>
带过渡动画的切换
为表格切换添加过渡效果:
<template>
<div>
<transition name="fade" mode="out-in">
<table v-if="showTable1" key="table1">
<!-- 表格1内容 -->
</table>
<table v-else key="table2">
<!-- 表格2内容 -->
</table>
</transition>
</div>
</template>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
选择哪种实现方式取决于具体需求。动态数据切换适合数据结构相同的表格,组件切换适合结构差异大的表格,条件渲染适合简单的切换场景,第三方组件能快速实现专业效果。







