vue 实现tab切换
Vue 实现 Tab 切换的方法
使用动态组件 <component :is>
通过 Vue 的动态组件特性,结合 v-for 和 v-if 实现 Tab 切换:
<template>
<div>
<div class="tab-buttons">
<button
v-for="(tab, index) in tabs"
:key="index"
@click="currentTab = tab.component"
:class="{ active: currentTab === tab.component }"
>
{{ tab.name }}
</button>
</div>
<component :is="currentTab" />
</div>
</template>
<script>
import Tab1 from './Tab1.vue';
import Tab2 from './Tab2.vue';
export default {
components: { Tab1, Tab2 },
data() {
return {
currentTab: 'Tab1',
tabs: [
{ name: 'Tab 1', component: 'Tab1' },
{ name: 'Tab 2', component: 'Tab2' }
]
};
}
};
</script>
<style>
.tab-buttons button.active {
background-color: #4CAF50;
color: white;
}
</style>
使用 v-show 控制显示
通过 v-show 切换不同 Tab 内容的显示状态:
<template>
<div>
<div class="tab-buttons">
<button
v-for="(tab, index) in tabs"
:key="index"
@click="currentTab = index"
:class="{ active: currentTab === index }"
>
{{ tab.name }}
</button>
</div>
<div class="tab-content">
<div v-show="currentTab === 0">Content for Tab 1</div>
<div v-show="currentTab === 1">Content for Tab 2</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentTab: 0,
tabs: [
{ name: 'Tab 1' },
{ name: 'Tab 2' }
]
};
}
};
</script>
使用 Vue Router 实现
结合 Vue Router 实现带路由的 Tab 切换:
// router.js
import Vue from 'vue';
import Router from 'vue-router';
import Tab1 from './views/Tab1.vue';
import Tab2 from './views/Tab2.vue';
Vue.use(Router);
export default new Router({
routes: [
{ path: '/tab1', component: Tab1 },
{ path: '/tab2', component: Tab2 }
]
});
<!-- App.vue -->
<template>
<div>
<router-link to="/tab1" tag="button">Tab 1</router-link>
<router-link to="/tab2" tag="button">Tab 2</router-link>
<router-view></router-view>
</div>
</template>
使用第三方库
可以使用现成的 Vue Tab 组件库,如 vue-tabs-component:

npm install vue-tabs-component
import { Tabs, Tab } from 'vue-tabs-component';
export default {
components: { Tabs, Tab }
};
<template>
<tabs>
<tab name="First tab">
Content for first tab
</tab>
<tab name="Second tab">
Content for second tab
</tab>
</tabs>
</template>
注意事项
- 动态组件方法适合不同 Tab 内容差异较大的场景
v-show方法适合简单的内容切换,所有 Tab 内容会同时存在于 DOM 中- Vue Router 方法适合需要 URL 同步的场景
- 第三方库可以提供更多高级功能如动画、懒加载等






