vue怎么实现tab
Vue 实现 Tab 的常见方法
使用动态组件和 v-if/v-show
通过动态组件或条件渲染(v-if/v-show)切换不同内容区域,结合点击事件改变当前激活的标签。
<template>
<div>
<div class="tabs">
<button
v-for="(tab, index) in tabs"
:key="index"
@click="currentTab = tab"
:class="{ active: currentTab === tab }"
>
{{ tab }}
</button>
</div>
<div class="content">
<div v-if="currentTab === 'Tab1'">内容1</div>
<div v-if="currentTab === 'Tab2'">内容2</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
tabs: ['Tab1', 'Tab2'],
currentTab: 'Tab1'
}
}
}
</script>
<style>
.active {
background-color: #42b983;
color: white;
}
</style>
使用 Vue Router
如果 Tab 需要与路由关联,可以通过 Vue Router 实现导航切换。
<template>
<div>
<router-link to="/tab1" tag="button">Tab1</router-link>
<router-link to="/tab2" tag="button">Tab2</router-link>
<router-view></router-view>
</div>
</template>
使用第三方 UI 库
许多 Vue UI 库(如 Element UI、Vuetify、Ant Design Vue)提供了现成的 Tab 组件,可直接使用。
以 Element UI 为例:
<template>
<el-tabs v-model="activeTab">
<el-tab-pane label="Tab1" name="tab1">内容1</el-tab-pane>
<el-tab-pane label="Tab2" name="tab2">内容2</el-tab-pane>
</el-tabs>
</template>
<script>
export default {
data() {
return {
activeTab: 'tab1'
}
}
}
</script>
自定义 Tab 组件
封装可复用的 Tab 组件,通过插槽(slot)传递内容。
<!-- Tab.vue -->
<template>
<div>
<div class="tab-header">
<div
v-for="(tab, index) in tabs"
:key="index"
@click="selectTab(index)"
:class="{ active: currentIndex === index }"
>
{{ tab.label }}
</div>
</div>
<div class="tab-content">
<slot :name="tabs[currentIndex].slotName"></slot>
</div>
</div>
</template>
<script>
export default {
props: {
tabs: Array,
initialTab: Number
},
data() {
return {
currentIndex: this.initialTab || 0
}
},
methods: {
selectTab(index) {
this.currentIndex = index
}
}
}
</script>
使用自定义组件:
<template>
<Tab :tabs="[
{ label: 'Tab1', slotName: 'tab1' },
{ label: 'Tab2', slotName: 'tab2' }
]">
<template v-slot:tab1>内容1</template>
<template v-slot:tab2>内容2</template>
</Tab>
</template>
以上方法可根据项目需求选择,简单场景可用条件渲染,复杂场景建议使用路由或 UI 库组件。







