vue 路由实现tab切换
Vue 路由实现 Tab 切换
在 Vue 中,可以通过 Vue Router 结合动态组件或路由参数实现 Tab 切换功能。以下是两种常见方法:
方法一:基于路由参数的 Tab 切换
通过路由参数动态渲染不同 Tab 内容,适合需要记录 Tab 状态的场景。
-
定义路由配置,使用动态参数(如
:tabName):// router.js const routes = [ { path: '/tabs/:tabName', component: TabsContainer, props: true // 将路由参数作为 props 传递 } ] -
创建 Tab 容器组件,通过
watch或computed响应参数变化:<template> <div> <nav> <router-link v-for="tab in tabs" :key="tab.name" :to="{ path: `/tabs/${tab.name}` }" > {{ tab.label }} </router-link> </nav> <component :is="currentTabComponent"/> </div> </template>
方法二:使用嵌套路由实现 Tab

适合需要独立子路由的场景,每个 Tab 可拥有自己的子路由栈。
-
配置嵌套路由:
const routes = [ { path: '/tabs', component: TabsContainer, children: [ { path: 'home', component: HomeTab }, { path: 'profile', component: ProfileTab }, { path: '', redirect: 'home' } // 默认重定向 ] } ] -
在父组件中使用
<router-view>渲染子路由:
<template> <div> <router-link v-for="tab in tabs" :key="tab.path" :to="{ path: `/tabs/${tab.path}` }" > {{ tab.label }} </router-link> <router-view/> </div> </template>
样式优化建议
-
为当前激活的 Tab 添加样式类:
.router-link-active { font-weight: bold; border-bottom: 2px solid #42b983; } -
使用 Vue Router 的
exact属性精确匹配:<router-link :to="..." exact-active-class="active-exact">
注意事项
- 路由模式应选用
history或hash根据项目需求 - 对于动态 Tab,可通过
beforeRouteUpdate守卫处理参数变化 - 保持 Tab 切换时的状态可使用
<keep-alive>包裹<router-view>
以上方法可根据项目复杂度选择,简单场景推荐方法一,需要复杂路由管理的推荐方法二。






