vue实现tab功能
Vue 实现 Tab 功能的方法
使用动态组件和 v-if 指令
通过 v-if 或 v-show 控制不同 Tab 内容的显示与隐藏。这种方法适合简单的 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>
<div class="tab-content">
<div v-if="currentTab === 'Tab1'">内容 1</div>
<div v-if="currentTab === 'Tab2'">内容 2</div>
<div v-if="currentTab === 'Tab3'">内容 3</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
tabs: ['Tab1', 'Tab2', 'Tab3'],
currentTab: 'Tab1'
};
}
};
</script>
<style>
.active {
background-color: #42b983;
color: white;
}
</style>
使用 Vue Router 实现路由级 Tab
通过 Vue Router 的嵌套路由实现 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></router-view>
</div>
</template>
<script>
export default {
data() {
return {
tabs: [
{ path: '/tab1', name: 'Tab1' },
{ path: '/tab2', name: 'Tab2' },
{ path: '/tab3', name: 'Tab3' }
]
};
}
};
</script>
使用第三方组件库
Element UI、Ant Design Vue 等库提供现成的 Tab 组件,适合快速集成。
<template>
<el-tabs v-model="activeTab">
<el-tab-pane label="Tab1" name="tab1">内容 1</el-tab-pane>
<el-tab-pane label="Tab2" name="tab2">内容 2</el-tab-pane>
<el-tab-pane label="Tab3" name="tab3">内容 3</el-tab-pane>
</el-tabs>
</template>
<script>
export default {
data() {
return {
activeTab: 'tab1'
};
}
};
</script>
封装可复用的 Tab 组件
通过插槽(Slots)和动态组件实现高度自定义的 Tab 功能。
<template>
<div>
<div class="tab-header">
<div
v-for="(tab, index) in tabs"
:key="index"
@click="setActiveTab(index)"
:class="{ active: activeTab === index }"
>
{{ tab.title }}
</div>
</div>
<div class="tab-body">
<slot :name="tabs[activeTab].slotName"></slot>
</div>
</div>
</template>
<script>
export default {
props: {
tabs: {
type: Array,
required: true
},
initialTab: {
type: Number,
default: 0
}
},
data() {
return {
activeTab: this.initialTab
};
},
methods: {
setActiveTab(index) {
this.activeTab = index;
}
}
};
</script>
注意事项
- 性能优化:对于复杂内容,使用
v-show替代v-if避免重复渲染。 - 动画效果:可以通过
<transition>组件为 Tab 切换添加动画。 - 状态保持:使用
<keep-alive>缓存动态组件状态。
以上方法可根据实际需求灵活选择或组合使用。






