vue实现滑动tab
Vue 实现滑动 Tab 的方法
使用 Vue 和 CSS 实现基础滑动 Tab
通过 Vue 的响应式数据和 CSS 过渡效果实现滑动 Tab。以下是一个基础实现示例:

<template>
<div class="tab-container">
<div class="tab-header">
<div
v-for="(tab, index) in tabs"
:key="index"
class="tab-item"
:class="{ 'active': activeTab === index }"
@click="activeTab = index"
>
{{ tab.title }}
</div>
<div class="tab-indicator" :style="indicatorStyle"></div>
</div>
<div class="tab-content">
<div
v-for="(tab, index) in tabs"
:key="index"
v-show="activeTab === index"
>
{{ tab.content }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
activeTab: 0,
tabs: [
{ title: 'Tab 1', content: 'Content 1' },
{ title: 'Tab 2', content: 'Content 2' },
{ title: 'Tab 3', content: 'Content 3' }
]
}
},
computed: {
indicatorStyle() {
return {
width: `${100 / this.tabs.length}%`,
transform: `translateX(${this.activeTab * 100}%)`
}
}
}
}
</script>
<style>
.tab-container {
width: 100%;
}
.tab-header {
display: flex;
position: relative;
border-bottom: 1px solid #ddd;
}
.tab-item {
flex: 1;
text-align: center;
padding: 10px;
cursor: pointer;
}
.tab-item.active {
color: #42b983;
}
.tab-indicator {
position: absolute;
bottom: 0;
height: 2px;
background-color: #42b983;
transition: transform 0.3s ease;
}
.tab-content {
padding: 20px;
}
</style>
使用第三方库实现更复杂效果
如果需要更复杂的滑动效果,可以使用 vue-slick 或 swiper-vue 等库。以下是使用 swiper-vue 的示例:

<template>
<swiper
:slides-per-view="3"
:space-between="10"
@swiper="onSwiper"
@slideChange="onSlideChange"
>
<swiper-slide v-for="(tab, index) in tabs" :key="index">
<div @click="activeTab = index" :class="{ 'active': activeTab === index }">
{{ tab.title }}
</div>
</swiper-slide>
</swiper>
<div class="tab-content">
{{ tabs[activeTab].content }}
</div>
</template>
<script>
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/swiper-bundle.css'
export default {
components: {
Swiper,
SwiperSlide
},
data() {
return {
activeTab: 0,
tabs: [
{ title: 'Tab 1', content: 'Content 1' },
{ title: 'Tab 2', content: 'Content 2' },
{ title: 'Tab 3', content: 'Content 3' }
],
swiper: null
}
},
methods: {
onSwiper(swiper) {
this.swiper = swiper
},
onSlideChange() {
this.activeTab = this.swiper.activeIndex
}
}
}
</script>
响应式设计考虑
对于移动端适配,可以添加媒体查询调整 Tab 的显示方式:
@media (max-width: 768px) {
.tab-header {
overflow-x: auto;
white-space: nowrap;
display: block;
}
.tab-item {
display: inline-block;
width: auto;
padding: 10px 20px;
}
.tab-indicator {
display: none;
}
}
性能优化建议
对于大量 Tab 内容,可以使用 keep-alive 缓存已访问的 Tab:
<template>
<div class="tab-content">
<keep-alive>
<component :is="tabs[activeTab].component" v-if="tabs[activeTab].component" />
</keep-alive>
</div>
</template>
以上方法提供了从基础到进阶的 Vue 滑动 Tab 实现方案,可根据项目需求选择合适的实现方式。






