vue组件实现tab
Vue 组件实现 Tab 切换功能
基础实现方案
创建两个组件:Tabs.vue(父组件)和 Tab.vue(子组件)。父组件管理当前激活的 tab,子组件作为单个 tab 的内容容器。
Tabs.vue
<template>
<div class="tabs">
<div class="tabs-header">
<button
v-for="(tab, index) in tabs"
:key="index"
@click="currentTab = index"
:class="{ active: currentTab === index }"
>
{{ tab.title }}
</button>
</div>
<div class="tabs-content">
<slot></slot>
</div>
</div>
</template>
<script>
export default {
data() {
return {
tabs: [],
currentTab: 0
}
},
mounted() {
this.tabs = this.$children.map(child => ({
title: child.title
}))
}
}
</script>
<style>
.tabs-header button.active {
background: #ddd;
}
</style>
Tab.vue

<template>
<div v-show="isActive">
<slot></slot>
</div>
</template>
<script>
export default {
props: {
title: {
type: String,
required: true
}
},
computed: {
isActive() {
return this.$parent.currentTab === this.$parent.tabs.findIndex(tab => tab.title === this.title)
}
}
}
</script>
使用示例
<tabs>
<tab title="Tab 1">
Content for tab 1
</tab>
<tab title="Tab 2">
Content for tab 2
</tab>
<tab title="Tab 3">
Content for tab 3
</tab>
</tabs>
进阶优化方案
使用 provide/inject 代替直接访问 $parent,使组件更解耦:
Tabs.vue

<script>
export default {
provide() {
return {
tabsProvider: this
}
},
// 其余代码不变
}
</script>
Tab.vue
<script>
export default {
inject: ['tabsProvider'],
computed: {
isActive() {
return this.tabsProvider.currentTab === this.tabsProvider.tabs.findIndex(tab => tab.title === this.title)
}
}
}
</script>
动画效果实现
为 tab 内容切换添加过渡动画:
<template>
<transition name="fade" mode="out-in">
<div v-show="isActive" :key="title">
<slot></slot>
</div>
</transition>
</template>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
响应式设计
添加响应式样式,使 tabs 在移动设备上表现良好:
.tabs-header {
display: flex;
overflow-x: auto;
}
.tabs-header button {
white-space: nowrap;
padding: 10px 20px;
border: none;
background: none;
cursor: pointer;
}
@media (max-width: 768px) {
.tabs-header {
flex-wrap: wrap;
}
.tabs-header button {
flex: 1 0 auto;
}
}






