vue实现tab组件
Vue 实现 Tab 组件
基础实现思路
通过 Vue 的动态组件和 v-for 指令可以快速实现 Tab 组件。核心是利用 currentTab 变量控制当前显示的选项卡内容。
<template>
<div class="tabs">
<div class="tab-header">
<button
v-for="(tab, index) in tabs"
:key="index"
@click="currentTab = index"
:class="{ active: currentTab === index }"
>
{{ tab.title }}
</button>
</div>
<div class="tab-content">
<component :is="tabs[currentTab].content" />
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentTab: 0,
tabs: [
{ title: 'Tab 1', content: 'TabContent1' },
{ title: 'Tab 2', content: 'TabContent2' }
]
}
}
}
</script>
<style>
.tab-header button.active {
background-color: #ddd;
}
</style>
组件化封装
将 Tab 组件拆分为可复用的父子组件结构更合理:
<!-- TabContainer.vue -->
<template>
<div class="tab-container">
<slot></slot>
</div>
</template>
<!-- TabItem.vue -->
<template>
<div v-show="isActive">
<slot></slot>
</div>
</template>
<script>
export default {
props: {
title: String
},
data() {
return {
isActive: false
}
}
}
</script>
使用方法
<template>
<tab-container>
<tab-item title="Tab 1">
Content for Tab 1
</tab-item>
<tab-item title="Tab 2">
Content for Tab 2
</tab-item>
</tab-container>
</template>
动态控制
通过 provide/inject 实现父子组件通信:
// TabContainer.vue
export default {
provide() {
return {
tabProvider: this
}
},
data() {
return {
activeIndex: 0
}
}
}
// TabItem.vue
export default {
inject: ['tabProvider'],
mounted() {
this.isActive = this.tabProvider.activeIndex === this.index
}
}
动画效果
添加过渡动画提升用户体验:
<transition name="fade" mode="out-in">
<div v-show="isActive" class="tab-content">
<slot></slot>
</div>
</transition>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
响应式设计
使用 CSS 实现响应式布局:
.tab-header {
display: flex;
flex-wrap: wrap;
}
.tab-header button {
flex: 1;
min-width: 120px;
}
@media (max-width: 600px) {
.tab-header {
flex-direction: column;
}
}
路由集成
结合 Vue Router 实现路由选项卡:
watch: {
'$route'(to) {
this.currentTab = this.tabs.findIndex(tab => tab.path === to.path)
}
}






