vue-router实现tab
Vue Router 实现 Tab 功能
在 Vue.js 项目中,使用 vue-router 实现 Tab 功能可以通过动态路由和组件切换来完成。以下是实现方法:
路由配置
在 router/index.js 中配置路由,为每个 Tab 分配一个路由路径:
const routes = [
{
path: '/',
redirect: '/tab1'
},
{
path: '/tab1',
component: () => import('@/views/Tab1.vue')
},
{
path: '/tab2',
component: () => import('@/views/Tab2.vue')
},
{
path: '/tab3',
component: () => import('@/views/Tab3.vue')
}
]
Tab 导航组件
创建一个 Tab 导航组件,使用 router-link 实现路由跳转:
<template>
<div class="tabs">
<router-link to="/tab1" active-class="active">Tab 1</router-link>
<router-link to="/tab2" active-class="active">Tab 2</router-link>
<router-link to="/tab3" active-class="active">Tab 3</router-link>
</div>
</template>
<style>
.tabs {
display: flex;
gap: 10px;
}
.active {
color: #42b983;
font-weight: bold;
}
</style>
路由视图
在主组件中使用 router-view 显示当前 Tab 内容:
<template>
<div>
<TabNavigation />
<router-view />
</div>
</template>
动态路由匹配
如果需要动态生成 Tabs,可以使用参数化路由:
{
path: '/tab/:id',
component: () => import('@/views/DynamicTab.vue')
}
保持 Tab 状态
使用 keep-alive 缓存 Tab 组件状态:
<router-view v-slot="{ Component }">
<keep-alive>
<component :is="Component" />
</keep-alive>
</router-view>
嵌套路由
对于复杂 Tab 结构,可以使用嵌套路由:
{
path: '/dashboard',
component: Dashboard,
children: [
{
path: 'stats',
component: Stats
},
{
path: 'settings',
component: Settings
}
]
}
编程式导航
在脚本中通过 this.$router.push() 切换 Tab:
methods: {
switchTab(tabName) {
this.$router.push(`/tab/${tabName}`)
}
}
通过以上方法,可以实现功能完整且可扩展的 Tab 系统,满足不同场景的需求。







