vue 实现table切换
Vue 实现 Table 切换的方法
使用 v-if 或 v-show 切换不同表格
通过条件渲染指令 v-if 或 v-show 可以快速切换不同的表格组件。v-if 是惰性的,适合切换频率低的场景;v-show 通过 CSS 控制显示,适合频繁切换。
<template>
<div>
<button @click="currentTable = 'table1'">显示表格1</button>
<button @click="currentTable = 'table2'">显示表格2</button>
<table1 v-if="currentTable === 'table1'" />
<table2 v-if="currentTable === 'table2'" />
</div>
</template>
<script>
export default {
data() {
return {
currentTable: 'table1'
}
}
}
</script>
动态组件实现表格切换
使用 Vue 的 <component> 动态组件可以更灵活地切换表格,适合需要根据条件动态渲染不同组件的场景。
<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>
通过路由切换表格页面
如果表格需要作为独立页面展示,可以使用 Vue Router 实现路由级别的切换。
// router.js
const routes = [
{ path: '/table1', component: Table1 },
{ path: '/table2', component: Table2 }
]
<template>
<div>
<router-link to="/table1">表格1</router-link>
<router-link to="/table2">表格2</router-link>
<router-view></router-view>
</div>
</template>
同一表格动态切换数据源
保持表格组件不变,仅通过改变数据源实现内容切换,适合表格结构相同但数据不同的场景。
<template>
<div>
<button @click="loadData('data1')">加载数据1</button>
<button @click="loadData('data2')">加载数据2</button>
<table>
<tr v-for="item in tableData" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [],
dataSources: {
data1: [{ id: 1, name: '数据1' }],
data2: [{ id: 2, name: '数据2' }]
}
}
},
methods: {
loadData(source) {
this.tableData = this.dataSources[source]
}
}
}
</script>
使用第三方表格组件切换
对于 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 v-if="currentTable === 'table1'" :data="data1"></el-table>
<el-table v-if="currentTable === 'table2'" :data="data2"></el-table>
</div>
</template>
以上方法可根据实际需求选择使用,简单场景推荐使用条件渲染,复杂场景可考虑动态组件或路由方案。数据驱动的方式在维护性和性能上通常更有优势。







