vue实现tabs标签
使用 Vue 实现 Tabs 标签页
基础实现
创建一个 Tabs 组件,包含标签页头和内容区域。通过 v-for 动态渲染标签页,使用 v-show 或 v-if 控制内容显示。
<template>
<div class="tabs">
<div class="tabs-header">
<div
v-for="(tab, index) in tabs"
:key="index"
@click="activeTab = index"
:class="{ 'active': activeTab === index }"
>
{{ tab.title }}
</div>
</div>
<div class="tabs-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>
.tabs-header {
display: flex;
border-bottom: 1px solid #ccc;
}
.tabs-header div {
padding: 10px 20px;
cursor: pointer;
}
.tabs-header div.active {
border-bottom: 2px solid #42b983;
}
.tabs-content {
padding: 20px;
}
</style>
动态添加/删除标签页
通过方法动态操作 tabs 数组实现标签页的增删功能。
methods: {
addTab() {
this.tabs.push({
title: `Tab ${this.tabs.length + 1}`,
content: `Content ${this.tabs.length + 1}`
})
},
removeTab(index) {
this.tabs.splice(index, 1)
if (this.activeTab >= this.tabs.length) {
this.activeTab = this.tabs.length - 1
}
}
}
使用插槽实现灵活内容
通过具名插槽允许父组件自定义标签页内容。
<template>
<div class="tabs">
<div class="tabs-header">
<div
v-for="(tab, index) in tabs"
:key="index"
@click="activeTab = index"
:class="{ 'active': activeTab === index }"
>
{{ tab.title }}
</div>
</div>
<div class="tabs-content">
<slot :name="`tab-${activeTab}`"></slot>
</div>
</div>
</template>
父组件使用方式:

<tabs>
<template v-slot:tab-0>
<custom-component-1 />
</template>
<template v-slot:tab-1>
<custom-component-2 />
</template>
</tabs>
动画过渡效果
使用 Vue 的 <transition> 组件为标签页切换添加动画效果。
<div class="tabs-content">
<transition name="fade" mode="out-in">
<div :key="activeTab">
{{ tabs[activeTab].content }}
</div>
</transition>
</div>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
响应式设计
通过媒体查询确保标签页在不同设备上表现良好。

@media (max-width: 768px) {
.tabs-header {
flex-direction: column;
}
.tabs-header div {
border-bottom: 1px solid #ddd;
}
.tabs-header div.active {
border-bottom: 2px solid #42b983;
}
}
可复用组件模式
将 Tabs 组件拆分为多个子组件提高复用性。
<template>
<div class="tabs">
<tabs-header
:tabs="tabs"
:active-tab="activeTab"
@tab-change="activeTab = $event"
/>
<tabs-content
:tabs="tabs"
:active-tab="activeTab"
/>
</div>
</template>
状态管理
对于复杂应用,可以使用 Vuex 管理标签页状态。
// store.js
export default new Vuex.Store({
state: {
tabs: [],
activeTab: 0
},
mutations: {
ADD_TAB(state, tab) {
state.tabs.push(tab)
},
SET_ACTIVE_TAB(state, index) {
state.activeTab = index
}
}
})
路由集成
将标签页与 Vue Router 集成,实现 URL 同步。
watch: {
'$route.query.tab'(newTab) {
this.activeTab = Number(newTab) || 0
},
activeTab(newTab) {
this.$router.replace({
query: { ...this.$route.query, tab: newTab }
})
}
}






