vue怎么实现tab
Vue 实现 Tab 的方法
使用 v-if 和 v-show 动态切换内容
在 Vue 中可以通过 v-if 或 v-show 指令结合点击事件动态切换 Tab 内容。v-if 会销毁和重建 DOM 元素,适合内容切换不频繁的场景;v-show 仅切换 CSS 的 display 属性,适合频繁切换的场景。
<template>
<div>
<div class="tab-header">
<button
v-for="(tab, index) in tabs"
:key="index"
@click="currentTab = tab.id"
:class="{ active: currentTab === tab.id }"
>
{{ tab.name }}
</button>
</div>
<div class="tab-content">
<div v-if="currentTab === 'tab1'">内容 1</div>
<div v-if="currentTab === 'tab2'">内容 2</div>
<div v-if="currentTab === 'tab3'">内容 3</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentTab: 'tab1',
tabs: [
{ id: 'tab1', name: 'Tab 1' },
{ id: 'tab2', name: 'Tab 2' },
{ id: 'tab3', name: 'Tab 3' }
]
};
}
};
</script>
<style>
.tab-header button {
padding: 10px 20px;
cursor: pointer;
}
.tab-header button.active {
background-color: #42b983;
color: white;
}
</style>
使用动态组件 <component :is>
动态组件更适合复杂 Tab 内容,每个 Tab 可以拆分为独立的组件,通过 :is 动态加载。
<template>
<div>
<div class="tab-header">
<button
v-for="(tab, index) in tabs"
:key="index"
@click="currentTab = tab.component"
:class="{ active: currentTab === tab.component }"
>
{{ tab.name }}
</button>
</div>
<div class="tab-content">
<component :is="currentTab" />
</div>
</div>
</template>
<script>
import Tab1 from './Tab1.vue';
import Tab2 from './Tab2.vue';
import Tab3 from './Tab3.vue';
export default {
components: { Tab1, Tab2, Tab3 },
data() {
return {
currentTab: 'Tab1',
tabs: [
{ component: 'Tab1', name: 'Tab 1' },
{ component: 'Tab2', name: 'Tab 2' },
{ component: 'Tab3', name: 'Tab 3' }
]
};
}
};
</script>
使用 Vue Router 实现路由级 Tab
如果需要 Tab 切换时同步 URL 变化,可以结合 Vue Router 的嵌套路由实现。
// router.js
const routes = [
{
path: '/tabs',
component: TabsContainer,
children: [
{ path: 'tab1', component: Tab1 },
{ path: 'tab2', component: Tab2 },
{ path: '', redirect: 'tab1' } // 默认重定向
]
}
];
<!-- TabsContainer.vue -->
<template>
<div>
<router-link
v-for="(tab, index) in tabs"
:key="index"
:to="`/tabs/${tab.path}`"
active-class="active"
>
{{ tab.name }}
</router-link>
<router-view></router-view>
</div>
</template>
使用第三方库
如果需要更丰富的功能(如动画、响应式设计),可以使用第三方库如:
安装后直接调用组件即可:
<tabs>
<tab name="Tab 1">内容 1</tab>
<tab name="Tab 2">内容 2</tab>
</tabs>
注意事项
- 如果 Tab 内容包含复杂状态或表单,优先使用
v-show避免重新渲染。 - 动态组件需提前注册或在异步组件中加载。
- 路由级 Tab 需确保路由配置正确,避免页面刷新后状态丢失。







