vue实现tab页
Vue 实现 Tab 页的方法
使用动态组件和 v-if 指令
通过 v-if 或 v-show 控制不同 Tab 内容的显示与隐藏。结合点击事件切换 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-if="currentTab === 0">内容 1</div>
<div v-if="currentTab === 1">内容 2</div>
<div v-if="currentTab === 2">内容 3</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
tabs: [
{ name: 'Tab 1' },
{ name: 'Tab 2' },
{ name: 'Tab 3' }
],
currentTab: 0
};
}
};
</script>
<style>
.active {
background-color: #42b983;
color: white;
}
</style>
使用 <component> 动态组件
通过 :is 动态绑定组件名,适合需要切换不同组件的场景。

<template>
<div>
<button @click="currentTab = 'Tab1'">Tab 1</button>
<button @click="currentTab = 'Tab2'">Tab 2</button>
<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'
};
}
};
</script>
使用 Vue Router 实现路由级 Tab
通过路由切换实现 Tab 页,适合复杂应用场景。
// router.js
const routes = [
{ path: '/tab1', component: Tab1 },
{ path: '/tab2', component: Tab2 }
];
<template>
<router-link to="/tab1">Tab 1</router-link>
<router-link to="/tab2">Tab 2</router-link>
<router-view></router-view>
</template>
使用第三方库(如 Element UI)
Element UI 等库提供封装好的 Tab 组件,可直接使用。
<template>
<el-tabs v-model="activeTab">
<el-tab-pane label="Tab 1" name="tab1">内容 1</el-tab-pane>
<el-tab-pane label="Tab 2" name="tab2">内容 2</el-tab-pane>
</el-tabs>
</template>
<script>
export default {
data() {
return {
activeTab: 'tab1'
};
}
};
</script>
注意事项
- 性能优化:频繁切换时用
v-show替代v-if(v-show通过 CSS 隐藏,v-if会销毁组件)。 - 动画效果:可通过
<transition>为 Tab 切换添加过渡动画。 - 状态保持:使用
<keep-alive>包裹动态组件以避免重复渲染。






