vue实现多表格切换
Vue实现多表格切换的方法
动态组件切换
使用Vue的<component>动态组件实现表格切换,通过is属性绑定当前显示的表格组件:
<template>
<div>
<button @click="currentTable = 'TableA'">表格A</button>
<button @click="currentTable = 'TableB'">表格B</button>
<component :is="currentTable"></component>
</div>
</template>
<script>
import TableA from './TableA.vue'
import TableB from './TableB.vue'
export default {
components: { TableA, TableB },
data() {
return {
currentTable: 'TableA'
}
}
}
</script>
v-if条件渲染
通过v-if/v-else-if控制不同表格的显示状态:

<template>
<div>
<button @click="activeTable = 1">表格1</button>
<button @click="activeTable = 2">表格2</button>
<Table1 v-if="activeTable === 1" />
<Table2 v-else-if="activeTable === 2" />
</div>
</template>
路由参数切换
在路由配置中定义参数实现表格切换:

// router.js
{
path: '/tables/:tableId',
component: TableContainer
}
<!-- TableContainer.vue -->
<template>
<component :is="`Table${$route.params.tableId}`" />
</template>
状态管理实现
使用Vuex管理当前显示的表格状态:
// store.js
export default new Vuex.Store({
state: {
currentTable: 'userTable'
},
mutations: {
setTable(state, tableName) {
state.currentTable = tableName
}
}
})
<template>
<div>
<button @click="$store.commit('setTable', 'userTable')">用户表</button>
<button @click="$store.commit('setTable', 'productTable')">产品表</button>
<UserTable v-if="$store.state.currentTable === 'userTable'" />
<ProductTable v-else />
</div>
</template>
数据驱动渲染
通过单一表格组件动态切换数据源:
<template>
<div>
<button @click="loadUserData">用户数据</button>
<button @click="loadProductData">产品数据</button>
<Table :data="tableData" :columns="currentColumns" />
</div>
</template>
<script>
export default {
data() {
return {
tableData: [],
currentColumns: []
}
},
methods: {
loadUserData() {
this.tableData = fetchUsers()
this.currentColumns = userColumns
},
loadProductData() {
this.tableData = fetchProducts()
this.currentColumns = productColumns
}
}
}
</script>
注意事项
- 频繁切换时考虑使用
<keep-alive>缓存表格组件 - 大型表格切换时注意内存管理
- 切换动画可使用Vue的过渡效果
- 移动端考虑使用选项卡(Tab)式UI






