vue实现选项卡分页
使用 Vue 实现选项卡分页
基础实现
通过 v-for 动态生成选项卡标题,利用 v-show 或 v-if 控制内容显示。
<template>
<div class="tabs">
<div class="tab-headers">
<button
v-for="(tab, index) in tabs"
:key="index"
@click="currentTab = index"
:class="{ active: currentTab === index }"
>
{{ tab.title }}
</button>
</div>
<div class="tab-contents">
<div
v-for="(tab, index) in tabs"
:key="index"
v-show="currentTab === index"
>
{{ tab.content }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentTab: 0,
tabs: [
{ title: 'Tab 1', content: 'Content 1' },
{ title: 'Tab 2', content: 'Content 2' },
{ title: 'Tab 3', content: 'Content 3' }
]
}
}
}
</script>
<style>
.tab-headers button.active {
background-color: #42b983;
color: white;
}
</style>
动态内容加载
结合异步组件或 API 请求实现按需加载内容。
methods: {
async loadContent(index) {
if (!this.tabs[index].loaded) {
const res = await fetch(`/api/content/${index}`);
this.tabs[index].content = await res.json();
this.tabs[index].loaded = true;
}
this.currentTab = index;
}
}
过渡动画效果
使用 Vue 的 <transition> 组件实现切换动画。
<transition name="fade" mode="out-in">
<div
v-for="(tab, index) in tabs"
v-show="currentTab === index"
:key="index"
>
{{ tab.content }}
</div>
</transition>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
可复用组件封装
将选项卡逻辑抽象为独立组件。
<!-- TabContainer.vue -->
<template>
<div class="tab-container">
<slot name="headers"></slot>
<slot name="contents"></slot>
</div>
</template>
<!-- 使用方式 -->
<tab-container>
<template v-slot:headers>
<button v-for="(tab, index) in tabs" @click="currentTab = index">
{{ tab.title }}
</button>
</template>
<template v-slot:contents>
<div v-for="(tab, index) in tabs" v-show="currentTab === index">
{{ tab.content }}
</div>
</template>
</tab-container>
响应式设计
通过 CSS 媒体查询实现移动端适配。

@media (max-width: 768px) {
.tab-headers {
flex-direction: column;
}
}






