vue如何实现tab页
Vue 实现 Tab 页的方法
使用动态组件
通过 Vue 的 <component :is="currentTab"> 动态切换组件,结合 v-for 渲染标签栏。

<template>
<div>
<div class="tabs">
<button
v-for="tab in tabs"
:key="tab.name"
@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 {
data() {
return {
currentTab: 'Tab1',
tabs: [
{ name: '标签1', component: 'Tab1' },
{ name: '标签2', component: 'Tab2' }
]
};
},
components: { Tab1, Tab2 }
};
</script>
使用路由切换
通过 Vue Router 实现 Tab 页,适合需要 URL 同步的场景。

<template>
<div>
<router-link
v-for="tab in tabs"
:key="tab.path"
:to="tab.path"
active-class="active"
>
{{ tab.name }}
</router-link>
<router-view />
</div>
</template>
<script>
export default {
data() {
return {
tabs: [
{ name: '标签1', path: '/tab1' },
{ name: '标签2', path: '/tab2' }
]
};
}
};
</script>
使用第三方库
例如 vue-tabs-component 快速实现:
npm install vue-tabs-component
<template>
<tabs>
<tab name="标签1">内容1</tab>
<tab name="标签2">内容2</tab>
</tabs>
</template>
<script>
import { Tabs, Tab } from 'vue-tabs-component';
export default {
components: { Tabs, Tab }
};
</script>
样式优化
为 Tab 页添加基础样式:
.tabs button {
padding: 8px 16px;
border: none;
background: #f0f0f0;
cursor: pointer;
}
.tabs button.active {
background: #42b983;
color: white;
}
注意事项
- 动态组件方式适合简单场景,路由方式适合复杂应用。
- 切换时可通过
keep-alive缓存组件状态:<keep-alive> <component :is="currentTab" /> </keep-alive> - 移动端可结合
swiper实现滑动切换。






