vue组件实现tab
Vue 组件实现 Tab 切换
基础实现方案
模板结构
使用 v-for 渲染标签页标题,通过 v-show 或 v-if 控制内容显示:
<template>
<div class="tabs">
<div class="tab-headers">
<div
v-for="(tab, index) in tabs"
:key="index"
@click="activeTab = index"
:class="{ 'active': activeTab === index }"
>
{{ tab.title }}
</div>
</div>
<div class="tab-contents">
<div
v-for="(tab, index) in tabs"
:key="index"
v-show="activeTab === index"
>
{{ tab.content }}
</div>
</div>
</div>
</template>
脚本逻辑
定义 tabs 数据和 activeTab 控制当前选中项:
<script>
export default {
data() {
return {
activeTab: 0,
tabs: [
{ title: 'Tab 1', content: 'Content 1' },
{ title: 'Tab 2', content: 'Content 2' }
]
};
}
};
</script>
动态组件优化
使用 <component :is> 动态加载组件,适合复杂内容场景:
<template>
<div class="tabs">
<div class="tab-headers">
<div
v-for="(tab, index) in tabs"
:key="index"
@click="activeTab = tab.component"
:class="{ 'active': activeComponent === tab.component }"
>
{{ tab.title }}
</div>
</div>
<component :is="activeComponent" />
</div>
</template>
注册组件
需提前注册动态组件:

<script>
import Tab1Content from './Tab1Content.vue';
import Tab2Content from './Tab2Content.vue';
export default {
data() {
return {
activeComponent: 'Tab1Content',
tabs: [
{ title: 'Tab 1', component: 'Tab1Content' },
{ title: 'Tab 2', component: 'Tab2Content' }
]
};
},
components: { Tab1Content, Tab2Content }
};
</script>
样式与交互增强
CSS 样式示例
为标签页添加基础交互样式:
<style scoped>
.tab-headers {
display: flex;
border-bottom: 1px solid #ddd;
}
.tab-headers div {
padding: 10px 20px;
cursor: pointer;
}
.tab-headers .active {
border-bottom: 2px solid #42b983;
color: #42b983;
}
.tab-contents {
padding: 20px;
}
</style>
封装为可复用组件
通过 props 接收外部配置,提升复用性:

<script>
export default {
props: {
tabs: {
type: Array,
required: true,
validator: value => value.every(tab => 'title' in tab && 'content' in tab)
},
initialTab: {
type: Number,
default: 0
}
},
data() {
return {
activeTab: this.initialTab
};
}
};
</script>
使用示例
父组件传入配置数据:
<template>
<Tabs :tabs="[
{ title: '用户管理', content: '用户列表...' },
{ title: '权限设置', content: '角色配置...' }
]" />
</template>
进阶功能扩展
路由集成
结合 Vue Router 实现路由标签页:
computed: {
activeTab: {
get() {
return this.$route.query.tab || 0;
},
set(value) {
this.$router.push({ query: { ...this.$route.query, tab: value } });
}
}
}
动画效果
添加过渡动画提升用户体验:
<transition name="fade" mode="out-in">
<div
v-for="(tab, index) in tabs"
v-show="activeTab === index"
:key="index"
>
{{ tab.content }}
</div>
</transition>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}






