vue实现tab页
Vue 实现 Tab 页
使用动态组件和 v-for 实现
在 Vue 中,可以通过动态组件和 v-for 实现 Tab 页功能。以下是一个示例代码:
<template>
<div>
<div class="tabs">
<button
v-for="(tab, index) in tabs"
:key="index"
@click="currentTab = tab"
:class="{ active: currentTab === tab }"
>
{{ tab }}
</button>
</div>
<component :is="currentTabComponent" />
</div>
</template>
<script>
export default {
data() {
return {
tabs: ['Home', 'About', 'Contact'],
currentTab: 'Home'
}
},
computed: {
currentTabComponent() {
return this.currentTab.toLowerCase() + '-component'
}
}
}
</script>
<style>
.tabs button {
padding: 10px 20px;
margin-right: 5px;
cursor: pointer;
}
.tabs button.active {
background-color: #42b983;
color: white;
}
</style>
使用路由实现
Vue Router 可以用于实现更复杂的 Tab 页功能,尤其是当每个 Tab 需要独立 URL 时:

<template>
<div>
<router-link
v-for="tab in tabs"
:key="tab.path"
:to="tab.path"
active-class="active"
>
{{ tab.name }}
</router-link>
<router-view />
</div>
</template>
<script>
export default {
data() {
return {
tabs: [
{ path: '/home', name: 'Home' },
{ path: '/about', name: 'About' },
{ path: '/contact', name: 'Contact' }
]
}
}
}
</script>
使用第三方库
对于更高级的需求,可以使用专门为 Vue 设计的 Tab 组件库:

npm install vue-tabs-component
<template>
<tabs>
<tab name="First tab">
Content for first tab
</tab>
<tab name="Second tab">
Content for second tab
</tab>
</tabs>
</template>
<script>
import { Tabs, Tab } from 'vue-tabs-component'
export default {
components: {
Tabs,
Tab
}
}
</script>
动画效果
可以为 Tab 切换添加过渡动画:
<transition name="fade" mode="out-in">
<component :is="currentTabComponent" />
</transition>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
保持 Tab 状态
当需要在 Tab 切换时保持组件状态,可以使用 <keep-alive>:
<keep-alive>
<component :is="currentTabComponent" />
</keep-alive>
这些方法提供了从简单到复杂的 Vue Tab 页实现方案,可以根据具体需求选择适合的方式。






