vue顶部tab实现
Vue 顶部 Tab 实现方法
使用动态组件切换
通过 Vue 的 <component :is="currentTab"> 动态组件实现内容切换:
<template>
<div>
<div class="tabs">
<button
v-for="tab in tabs"
:key="tab"
@click="currentTab = tab"
:class="{ active: currentTab === tab }"
>
{{ tab }}
</button>
</div>
<component :is="currentTab" />
</div>
</template>
<script>
export default {
data() {
return {
tabs: ['Home', 'About', 'Contact'],
currentTab: 'Home'
}
},
components: {
Home,
About,
Contact
}
}
</script>
<style>
.tabs button.active {
border-bottom: 2px solid #42b983;
}
</style>
使用路由实现
结合 Vue Router 实现带路由的顶部 Tab:

<template>
<nav>
<router-link
v-for="tab in tabs"
:key="tab.path"
:to="tab.path"
active-class="active"
>
{{ tab.name }}
</router-link>
</nav>
<router-view />
</template>
<script>
export default {
data() {
return {
tabs: [
{ path: '/home', name: 'Home' },
{ path: '/about', name: 'About' },
{ path: '/contact', name: 'Contact' }
]
}
}
}
</script>
使用第三方库
安装 vue-tabs 组件库:
npm install vue-nav-tab
使用示例:

<template>
<vue-nav-tab :tabs="tabs" v-model:active="activeTab" />
</template>
<script>
import VueNavTab from 'vue-nav-tab'
export default {
components: { VueNavTab },
data() {
return {
tabs: [
{ id: 1, title: 'Home' },
{ id: 2, title: 'Profile' },
{ id: 3, title: 'Messages' }
],
activeTab: 1
}
}
}
</script>
动画效果实现
为 Tab 切换添加过渡动画:
<transition name="fade" mode="out-in">
<component :is="currentTab" />
</transition>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
响应式 Tab 实现
当 Tab 数量过多时自动转为可滚动:
<div class="scrollable-tabs">
<div class="tabs-container">
<button v-for="tab in tabs" :key="tab">
{{ tab }}
</button>
</div>
</div>
<style>
.scrollable-tabs {
overflow-x: auto;
white-space: nowrap;
}
.tabs-container {
display: inline-block;
}
</style>






