vue实现tabs标签
Vue 实现 Tabs 标签的方法
使用动态组件和 v-for 循环
通过动态组件和 v-for 循环可以轻松实现 Tabs 标签功能。定义一个数组存储标签数据,使用 v-for 渲染标签头,通过 v-bind:is 动态切换内容。
<template>
<div>
<div class="tabs">
<div
v-for="(tab, index) in tabs"
:key="index"
@click="currentTab = tab"
:class="{ active: currentTab === tab }"
>
{{ tab.name }}
</div>
</div>
<component :is="currentTab.component" />
</div>
</template>
<script>
export default {
data() {
return {
currentTab: {},
tabs: [
{ name: 'Tab 1', component: 'Tab1' },
{ name: 'Tab 2', component: 'Tab2' }
]
}
},
mounted() {
this.currentTab = this.tabs[0]
}
}
</script>
使用 Vue Router 实现路由切换
结合 Vue Router 可以实现基于路由的 Tabs 标签,每个标签对应一个路由路径。
<template>
<div>
<router-link
v-for="(tab, index) in tabs"
:key="index"
:to="tab.path"
active-class="active"
>
{{ tab.name }}
</router-link>
<router-view></router-view>
</div>
</template>
<script>
export default {
data() {
return {
tabs: [
{ name: 'Tab 1', path: '/tab1' },
{ name: 'Tab 2', path: '/tab2' }
]
}
}
}
</script>
使用第三方库
使用成熟的第三方库如 vue-tabs-component 可以快速实现 Tabs 功能。

安装库:
npm install vue-tabs-component
使用示例:

<template>
<tabs>
<tab name="Tab 1">
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>
自定义 Tabs 组件
创建一个可复用的 Tabs 组件,通过插槽和 props 实现高度定制化。
<!-- Tabs.vue -->
<template>
<div class="tabs">
<div class="tabs-header">
<div
v-for="(tab, index) in tabs"
:key="index"
@click="selectTab(index)"
:class="{ active: activeTab === index }"
>
{{ tab.title }}
</div>
</div>
<div class="tabs-content">
<slot :name="`tab-${activeTab}`"></slot>
</div>
</div>
</template>
<script>
export default {
props: {
tabs: Array,
initialTab: {
type: Number,
default: 0
}
},
data() {
return {
activeTab: this.initialTab
}
},
methods: {
selectTab(index) {
this.activeTab = index
}
}
}
</script>
使用示例:
<template>
<Tabs :tabs="[{ title: 'Tab 1' }, { title: 'Tab 2' }]">
<template #tab-0>
Content for Tab 1
</template>
<template #tab-1>
Content for Tab 2
</template>
</Tabs>
</template>
以上方法提供了多种实现 Tabs 标签的途径,可以根据项目需求选择合适的方式。动态组件适合简单场景,Vue Router 适合需要路由管理的应用,第三方库可以快速集成,自定义组件则提供了最大的灵活性。






