vue 实现tab
Vue 实现 Tab 切换
在 Vue 中实现 Tab 切换功能可以通过动态组件或条件渲染完成。以下是两种常见方法:
动态组件实现
使用 Vue 的 <component> 动态组件结合 v-bind:is 实现 Tab 内容切换:

<template>
<div>
<div class="tab-buttons">
<button
v-for="(tab, index) in tabs"
:key="index"
@click="currentTab = tab"
:class="{ active: currentTab === tab }"
>
{{ tab }}
</button>
</div>
<component :is="currentTabComponent" class="tab-content"></component>
</div>
</template>
<script>
export default {
data() {
return {
tabs: ['Home', 'About', 'Contact'],
currentTab: 'Home'
}
},
computed: {
currentTabComponent() {
return `tab-${this.currentTab.toLowerCase()}`
}
}
}
</script>
条件渲染实现
通过 v-if 或 v-show 控制不同 Tab 内容的显示:
<template>
<div>
<div class="tab-buttons">
<button
v-for="(tab, index) in tabs"
:key="index"
@click="activeTab = index"
:class="{ active: activeTab === index }"
>
{{ tab }}
</button>
</div>
<div class="tab-content">
<div v-if="activeTab === 0">Home Content</div>
<div v-if="activeTab === 1">About Content</div>
<div v-if="activeTab === 2">Contact Content</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
tabs: ['Home', 'About', 'Contact'],
activeTab: 0
}
}
}
</script>
样式优化
为 Tab 添加基础样式提升用户体验:

.tab-buttons {
display: flex;
gap: 10px;
margin-bottom: 20px;
}
.tab-buttons button {
padding: 8px 16px;
cursor: pointer;
background: #f0f0f0;
border: none;
border-radius: 4px;
}
.tab-buttons button.active {
background: #42b983;
color: white;
}
.tab-content {
padding: 20px;
border: 1px solid #eee;
border-radius: 4px;
}
组件化方案
对于复杂场景,可将 Tab 封装为可复用组件:
<!-- TabContainer.vue -->
<template>
<div class="tab-container">
<slot></slot>
</div>
</template>
<!-- TabItem.vue -->
<template>
<div v-show="isActive" class="tab-item">
<slot></slot>
</div>
</template>
<script>
export default {
props: ['title'],
data() {
return {
isActive: false
}
}
}
</script>
路由集成
结合 Vue Router 实现基于路由的 Tab:
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/contact', component: Contact }
]
<router-link
v-for="(tab, index) in tabs"
:key="index"
:to="tab.path"
active-class="active"
>
{{ tab.name }}
</router-link>
<router-view></router-view>






