vue怎么实现 tab
Vue 实现 Tab 的方法
使用 v-if 和 v-show 控制显示
通过绑定 v-if 或 v-show 动态切换 Tab 内容,配合点击事件改变当前激活的 Tab 索引。
<template>
<div>
<div class="tabs">
<button
v-for="(tab, index) in tabs"
:key="index"
@click="activeTab = index"
:class="{ 'active': activeTab === index }"
>
{{ tab.title }}
</button>
</div>
<div class="tab-content">
<div v-show="activeTab === 0">
Content for Tab 1
</div>
<div v-show="activeTab === 1">
Content for Tab 2
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
activeTab: 0,
tabs: [
{ title: 'Tab 1' },
{ title: 'Tab 2' }
]
}
}
}
</script>
<style>
.active {
background-color: #42b983;
color: white;
}
</style>
使用动态组件 <component>
结合动态组件和 :is 属性,通过组件名动态渲染不同 Tab 内容。
<template>
<div>
<div class="tabs">
<button
v-for="(tab, index) in tabs"
:key="index"
@click="activeTab = tab.component"
:class="{ 'active': activeTab === tab.component }"
>
{{ tab.title }}
</button>
</div>
<component :is="activeTab" />
</div>
</template>
<script>
import Tab1 from './Tab1.vue'
import Tab2 from './Tab2.vue'
export default {
components: { Tab1, Tab2 },
data() {
return {
activeTab: 'Tab1',
tabs: [
{ title: 'Tab 1', component: 'Tab1' },
{ title: 'Tab 2', component: 'Tab2' }
]
}
}
}
</script>
使用 Vue Router 实现路由级 Tab
通过路由配置实现 Tab 切换,适合需要 URL 同步的场景。
// router.js
const routes = [
{ path: '/tab1', component: Tab1 },
{ path: '/tab2', component: Tab2 }
]
<template>
<div>
<router-link to="/tab1" active-class="active">Tab 1</router-link>
<router-link to="/tab2" active-class="active">Tab 2</router-link>
<router-view></router-view>
</div>
</template>
使用第三方库
例如 vue-tabs-component 快速实现功能完整的 Tab。
npm install vue-tabs-component
<template>
<tabs>
<tab name="First tab">
Content for first tab
</tab>
<tab name="Second tab">
Content for second tab
</tab>
</tabs>
</template>
<script>
import { Tabs, Tab } from 'vue-tabs-component'
export default {
components: { Tabs, Tab }
}
</script>
注意事项
- 性能考虑:
v-if会销毁组件,v-show仅切换显示(适合频繁切换)。 - 路由方式适合需要浏览器历史记录的场景。
- 动态组件方式适合需要复用独立逻辑的场景。







