vue tab实现
Vue Tab 实现方法
使用动态组件实现 Tab
在 Vue 中可以通过动态组件 <component :is="currentTab"> 结合 v-for 和 v-bind 实现 Tab 切换功能。以下是一个基础实现示例:
<template>
<div>
<div class="tabs">
<button
v-for="tab in tabs"
:key="tab.name"
@click="currentTab = tab.name"
:class="{ active: currentTab === tab.name }"
>
{{ tab.label }}
</button>
</div>
<component :is="currentTab" class="tab-content"></component>
</div>
</template>
<script>
import Tab1 from './Tab1.vue'
import Tab2 from './Tab2.vue'
export default {
components: { Tab1, Tab2 },
data() {
return {
currentTab: 'Tab1',
tabs: [
{ name: 'Tab1', label: 'Tab 1' },
{ name: 'Tab2', label: 'Tab 2' }
]
}
}
}
</script>
<style>
.tabs {
display: flex;
gap: 10px;
margin-bottom: 20px;
}
.tabs button {
padding: 8px 16px;
cursor: pointer;
background: none;
border: 1px solid #ddd;
border-radius: 4px;
}
.tabs button.active {
background: #007bff;
color: white;
border-color: #007bff;
}
.tab-content {
padding: 20px;
border: 1px solid #ddd;
border-radius: 4px;
}
</style>
使用 Vue Router 实现 Tab
对于更复杂的应用,可以结合 Vue Router 实现基于路由的 Tab:

// router.js
import { createRouter, createWebHistory } from 'vue-router'
import Tab1 from './views/Tab1.vue'
import Tab2 from './views/Tab2.vue'
const routes = [
{ path: '/tab1', component: Tab1 },
{ path: '/tab2', component: Tab2 }
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
<!-- App.vue -->
<template>
<nav>
<router-link to="/tab1">Tab 1</router-link>
<router-link to="/tab2">Tab 2</router-link>
</nav>
<router-view></router-view>
</template>
使用第三方库
对于更丰富的功能,可以考虑使用专门的 Vue Tab 组件库:
-
Vuetify Tabs:

<template> <v-tabs v-model="tab"> <v-tab v-for="item in items" :key="item"> {{ item }} </v-tab> </v-tabs> </template> -
Element Plus Tabs:
<template> <el-tabs v-model="activeName"> <el-tab-pane label="Tab 1" name="first">Content 1</el-tab-pane> <el-tab-pane label="Tab 2" name="second">Content 2</el-tab-pane> </el-tabs> </template>
动画效果
为 Tab 切换添加过渡动画:
<transition name="fade" mode="out-in">
<component :is="currentTab"></component>
</transition>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
以上方法可以根据项目需求选择适合的实现方式,从简单到复杂提供了多种解决方案。






