vue实现一个tab栏
实现基础Tab栏结构
使用Vue的v-for指令动态生成tab标题,结合v-show或v-if控制内容显示:
<template>
<div class="tab-container">
<div class="tab-header">
<div
v-for="(tab, index) in tabs"
:key="index"
@click="activeTab = index"
:class="{ 'active': activeTab === index }"
>
{{ tab.title }}
</div>
</div>
<div class="tab-content">
<div v-for="(tab, index) in tabs" :key="index" v-show="activeTab === index">
{{ tab.content }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
activeTab: 0,
tabs: [
{ title: 'Tab 1', content: 'Content 1' },
{ title: 'Tab 2', content: 'Content 2' },
{ title: 'Tab 3', content: 'Content 3' }
]
}
}
}
</script>
<style scoped>
.tab-header {
display: flex;
border-bottom: 1px solid #ddd;
}
.tab-header div {
padding: 10px 20px;
cursor: pointer;
}
.tab-header div.active {
border-bottom: 2px solid #42b983;
color: #42b983;
}
.tab-content {
padding: 20px;
}
</style>
使用组件化方式
将Tab栏拆分为可复用的组件结构:

<!-- TabContainer.vue -->
<template>
<div class="tab-container">
<div class="tab-header">
<slot name="header"></slot>
</div>
<div class="tab-content">
<slot name="content"></slot>
</div>
</div>
</template>
<!-- TabItem.vue -->
<template>
<div v-show="isActive">
<slot></slot>
</div>
</template>
<script>
export default {
props: {
title: String,
isActive: Boolean
}
}
</script>
<!-- 使用示例 -->
<template>
<TabContainer>
<template v-slot:header>
<div
v-for="(tab, index) in tabs"
:key="index"
@click="activateTab(index)"
:class="{ 'active': activeTab === index }"
>
{{ tab.title }}
</div>
</template>
<template v-slot:content>
<TabItem
v-for="(tab, index) in tabs"
:key="index"
:isActive="activeTab === index"
>
{{ tab.content }}
</TabItem>
</template>
</TabContainer>
</template>
添加动画效果
为tab内容切换添加过渡动画:
<template>
<transition name="fade" mode="out-in">
<div v-for="(tab, index) in tabs" :key="index" v-show="activeTab === index">
{{ tab.content }}
</div>
</transition>
</template>
<style scoped>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
响应式Tab栏
根据屏幕宽度自动调整Tab显示方式:

@media (max-width: 768px) {
.tab-header {
flex-direction: column;
}
.tab-header div {
border-bottom: 1px solid #eee;
}
}
动态添加/删除Tab
实现动态管理Tab的功能:
methods: {
addTab() {
this.tabs.push({
title: `Tab ${this.tabs.length + 1}`,
content: `New Content ${this.tabs.length + 1}`
})
},
removeTab(index) {
if (this.tabs.length <= 1) return
this.tabs.splice(index, 1)
if (this.activeTab >= index) {
this.activeTab = Math.max(0, this.activeTab - 1)
}
}
}
使用第三方库
如需更复杂功能,可考虑使用现成组件库:
npm install vue-tabs-component
import { Tabs, Tab } from 'vue-tabs-component'
export default {
components: {
Tabs, Tab
}
}
<tabs>
<tab name="First tab" :selected="true">
First tab content
</tab>
<tab name="Second tab">
Second tab content
</tab>
</tabs>






