vue 实现table切换
实现表格切换的基本思路
在Vue中实现表格切换功能,可以通过动态绑定数据源和条件渲染来实现。主要涉及v-if/v-show指令、动态组件或数据绑定。
方法一:使用v-if条件渲染
通过按钮切换不同的表格数据,利用v-if控制不同表格的显示隐藏。
<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.name }}</td>
</tr>
</table>
</div>
</template>
<script>
export default {
data() {
return {
currentTable: 'table1',
table1Data: [{ id: 1, name: '数据1' }],
table2Data: [{ id: 2, name: '数据2' }]
}
}
}
</script>
方法二:使用动态组件
通过<component :is="">动态加载不同的表格组件,适合更复杂的场景。
<template>
<div>
<button @click="currentComponent = 'Table1'">表格1</button>
<button @click="currentComponent = 'Table2'">表格2</button>
<component :is="currentComponent" />
</div>
</template>
<script>
import Table1 from './Table1.vue'
import Table2 from './Table2.vue'
export default {
components: { Table1, Table2 },
data() {
return {
currentComponent: 'Table1'
}
}
}
</script>
方法三:动态数据绑定
通过切换数据源实现表格内容变化,保持DOM结构不变。
<template>
<div>
<button @click="currentData = table1Data">表格1</button>
<button @click="currentData = table2Data">表格2</button>
<table>
<tr v-for="item in currentData" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
</div>
</template>
<script>
export default {
data() {
return {
currentData: [],
table1Data: [{ id: 1, name: '数据1' }],
table2Data: [{ id: 2, name: '数据2' }]
}
},
created() {
this.currentData = this.table1Data
}
}
</script>
方法四:结合路由切换
通过Vue Router实现不同路由对应不同表格,适合需要URL记录的场景。

// router.js
const routes = [
{ path: '/table1', component: Table1 },
{ path: '/table2', component: Table2 }
]
<!-- App.vue -->
<router-link to="/table1">表格1</router-link>
<router-link to="/table2">表格2</router-link>
<router-view></router-view>
性能优化建议
- 频繁切换时使用
v-show代替v-if(避免重复渲染) - 大数据量表格考虑虚拟滚动
- 相同结构的表格优先使用数据切换方案
完整示例(数据绑定方案)
<template>
<div>
<button
v-for="(tab, index) in tabs"
:key="index"
@click="activeTab = index"
>
{{ tab.name }}
</button>
<table>
<tr v-for="item in activeData" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.value }}</td>
</tr>
</table>
</div>
</template>
<script>
export default {
data() {
return {
activeTab: 0,
tabs: [
{ name: '表格A', data: [{id:1,name:'A1',value:100}] },
{ name: '表格B', data: [{id:2,name:'B1',value:200}] }
]
}
},
computed: {
activeData() {
return this.tabs[this.activeTab].data
}
}
}
</script>






