vue组件 实现tab切换
Vue 组件实现 Tab 切换
使用动态组件实现 Tab 切换
通过 Vue 的 <component :is="currentTab"> 动态切换组件,结合 v-for 渲染标签栏。
<template>
<div>
<div class="tab-buttons">
<button
v-for="tab in tabs"
:key="tab"
@click="currentTab = tab"
:class="{ active: currentTab === tab }"
>
{{ tab }}
</button>
</div>
<component :is="currentTab" class="tab-content"></component>
</div>
</template>
<script>
import Tab1 from './Tab1.vue';
import Tab2 from './Tab2.vue';
export default {
data() {
return {
tabs: ['Tab1', 'Tab2'],
currentTab: 'Tab1'
};
},
components: {
Tab1,
Tab2
}
};
</script>
<style>
.tab-buttons button {
padding: 8px 16px;
margin-right: 4px;
}
.tab-buttons button.active {
background: #42b983;
color: white;
}
</style>
使用 CSS 和 v-show 实现 Tab 切换
通过 v-show 控制内容显示,适合简单场景。

<template>
<div>
<div class="tab-buttons">
<button
v-for="tab in tabs"
:key="tab.name"
@click="currentTab = tab.name"
:class="{ active: currentTab === tab.name }"
>
{{ tab.label }}
</button>
</div>
<div class="tab-contents">
<div v-for="tab in tabs" :key="tab.name" v-show="currentTab === tab.name">
{{ tab.content }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentTab: 'home',
tabs: [
{ name: 'home', label: '首页', content: '首页内容' },
{ name: 'about', label: '关于', content: '关于内容' }
]
};
}
};
</script>
使用 Vue Router 实现 Tab 切换
适合需要 URL 同步的场景,结合路由配置。

// router.js
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
];
<template>
<div>
<router-link to="/" custom v-slot="{ navigate }">
<button @click="navigate" :class="{ active: $route.path === '/' }">
首页
</button>
</router-link>
<router-link to="/about" custom v-slot="{ navigate }">
<button @click="navigate" :class="{ active: $route.path === '/about' }">
关于
</button>
</router-link>
<router-view></router-view>
</div>
</template>
封装可复用的 Tab 组件
将 Tab 逻辑封装为独立组件,提高复用性。
<!-- Tabs.vue -->
<template>
<div class="tabs">
<div class="tab-header">
<div
v-for="tab in tabs"
:key="tab.name"
@click="selectTab(tab)"
:class="{ 'tab-active': isTabActive(tab) }"
>
{{ tab.label }}
</div>
</div>
<div class="tab-content">
<slot :name="currentTab.name"></slot>
</div>
</div>
</template>
<script>
export default {
props: {
tabs: Array,
initialTab: String
},
data() {
return {
currentTab: this.tabs.find(tab => tab.name === this.initialTab) || this.tabs[0]
};
},
methods: {
selectTab(tab) {
this.currentTab = tab;
},
isTabActive(tab) {
return this.currentTab.name === tab.name;
}
}
};
</script>
使用第三方库实现
例如 vue-tabs-component 提供开箱即用的解决方案。
npm install vue-tabs-component
<template>
<tabs>
<tab name="First tab">
First tab content
</tab>
<tab name="Second tab">
Second tab content
</tab>
</tabs>
</template>
<script>
import { Tabs, Tab } from 'vue-tabs-component';
export default {
components: {
Tabs,
Tab
}
};
</script>






