vue 怎么实现tab
Vue 实现 Tab 切换
在 Vue 中实现 Tab 切换功能可以通过动态组件或条件渲染(v-if/v-show)完成。以下是两种常见方法:

动态绑定 :is 实现 Tab
通过 :is 动态绑定组件名或组件对象,结合点击事件切换内容:

<template>
<div>
<div class="tab-buttons">
<button
v-for="tab in tabs"
:key="tab.name"
@click="currentTab = tab.name"
:class="{ active: currentTab === tab.name }"
>
{{ tab.label }}
</button>
</div>
<component :is="currentTabComponent" />
</div>
</template>
<script>
export default {
data() {
return {
tabs: [
{ name: 'HomeTab', label: 'Home' },
{ name: 'ProfileTab', label: 'Profile' }
],
currentTab: 'HomeTab'
};
},
computed: {
currentTabComponent() {
return this.currentTab;
}
},
components: {
HomeTab: { template: '<div>Home Content</div>' },
ProfileTab: { template: '<div>Profile Content</div>' }
}
};
</script>
<style>
.active {
background-color: #42b983;
color: white;
}
</style>
使用 v-if 或 v-show 控制显示
通过条件渲染控制 Tab 内容的显示与隐藏:
<template>
<div>
<div class="tab-buttons">
<button
v-for="tab in tabs"
:key="tab.id"
@click="activeTab = tab.id"
:class="{ active: activeTab === tab.id }"
>
{{ tab.label }}
</button>
</div>
<div class="tab-content">
<div v-if="activeTab === 'home'">Home Content</div>
<div v-if="activeTab === 'profile'">Profile Content</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
tabs: [
{ id: 'home', label: 'Home' },
{ id: 'profile', label: 'Profile' }
],
activeTab: 'home'
};
}
};
</script>
使用第三方库
如需更复杂的 Tab 功能(如动画、路由集成),可考虑以下库:
- Vuetify 的
v-tabs组件 - Element UI 的
el-tabs组件 - BootstrapVue 的
b-tabs组件
关键点
- 数据驱动:通过修改响应式数据(如
currentTab)触发视图更新。 - 样式控制:利用
:class绑定高亮状态。 - 性能考虑:频繁切换时用
v-show(仅切换 CSS 显示),内容差异大时用v-if(销毁/重建 DOM)。






