vue 实现tabs
Vue 实现 Tabs 组件
在 Vue 中实现 Tabs 组件可以通过多种方式完成,以下是几种常见的方法:
使用动态组件和 v-for 循环
通过动态组件和 v-for 循环可以轻松实现 Tabs 的基本功能。定义一个 tabs 数组,包含每个 Tab 的标题和内容,然后使用 v-for 渲染 Tab 标题,并通过 v-model 控制当前激活的 Tab。

<template>
<div class="tabs">
<div class="tabs-header">
<div
v-for="(tab, index) in tabs"
:key="index"
class="tab-header"
:class="{ active: activeTab === index }"
@click="activeTab = index"
>
{{ tab.title }}
</div>
</div>
<div class="tabs-content">
<component :is="tabs[activeTab].content" />
</div>
</div>
</template>
<script>
export default {
data() {
return {
activeTab: 0,
tabs: [
{ title: 'Tab 1', content: 'TabContent1' },
{ title: 'Tab 2', content: 'TabContent2' },
{ title: 'Tab 3', content: 'TabContent3' },
],
};
},
};
</script>
<style>
.tabs-header {
display: flex;
border-bottom: 1px solid #ccc;
}
.tab-header {
padding: 10px 20px;
cursor: pointer;
}
.tab-header.active {
border-bottom: 2px solid #42b983;
}
.tabs-content {
padding: 20px;
}
</style>
使用插槽(Slots)
通过插槽可以更灵活地定义 Tab 内容,适合需要自定义 Tab 内容的场景。定义一个 Tabs 组件和 Tab 子组件,通过插槽传递内容。
<!-- Tabs.vue -->
<template>
<div class="tabs">
<div class="tabs-header">
<div
v-for="(tab, index) in tabs"
:key="index"
class="tab-header"
:class="{ active: activeTab === index }"
@click="activeTab = index"
>
{{ tab.title }}
</div>
</div>
<div class="tabs-content">
<slot :name="`tab-${activeTab}`" />
</div>
</div>
</template>
<script>
export default {
data() {
return {
activeTab: 0,
tabs: [],
};
},
mounted() {
this.tabs = this.$slots.default
.filter((slot) => slot.componentOptions)
.map((slot) => ({
title: slot.componentOptions.propsData.title,
}));
},
};
</script>
<!-- Tab.vue -->
<template>
<div v-if="active" class="tab-content">
<slot />
</div>
</template>
<script>
export default {
props: {
title: String,
active: Boolean,
},
};
</script>
<!-- 使用方式 -->
<template>
<Tabs>
<Tab title="Tab 1">
Content for Tab 1
</Tab>
<Tab title="Tab 2">
Content for Tab 2
</Tab>
</Tabs>
</template>
使用第三方库
如果需要更复杂的功能(如动画、响应式设计等),可以直接使用成熟的第三方库,如 vue-tabs-component 或 bootstrap-vue。

安装 vue-tabs-component:
npm install vue-tabs-component
使用示例:
<template>
<tabs>
<tab name="Tab 1" :selected="true">
Content for Tab 1
</tab>
<tab name="Tab 2">
Content for Tab 2
</tab>
</tabs>
</template>
<script>
import { Tabs, Tab } from 'vue-tabs-component';
export default {
components: { Tabs, Tab },
};
</script>
注意事项
- 动态组件方式适合内容简单的场景,插槽方式适合需要高度自定义的场景。
- 第三方库通常提供更多功能(如动画、响应式设计),但会增加项目体积。
- 如果需要支持路由切换(如 Vue Router),可以结合
router-link实现。
以上方法可以根据实际需求选择,动态组件和插槽方式适合轻量级实现,第三方库适合功能丰富的场景。






