vue实现滑动tab
实现滑动Tab的基本思路
使用Vue实现滑动Tab通常需要结合CSS动画和动态数据绑定。核心是通过控制CSS的transform属性实现滑动效果,同时利用Vue的响应式特性更新内容。
基础HTML结构
<template>
<div class="tab-container">
<div class="tab-header">
<div
v-for="(tab, index) in tabs"
:key="index"
@click="selectTab(index)"
:class="{ 'active': currentIndex === index }"
>
{{ tab.title }}
</div>
</div>
<div class="tab-indicator" :style="indicatorStyle"></div>
<div class="tab-content">
<div
v-for="(tab, index) in tabs"
:key="index"
:class="{ 'active': currentIndex === index }"
>
{{ tab.content }}
</div>
</div>
</div>
</template>
Vue数据与逻辑
<script>
export default {
data() {
return {
tabs: [
{ title: 'Tab 1', content: 'Content 1' },
{ title: 'Tab 2', content: 'Content 2' },
{ title: 'Tab 3', content: 'Content 3' }
],
currentIndex: 0
}
},
computed: {
indicatorStyle() {
return {
width: `${100 / this.tabs.length}%`,
transform: `translateX(${100 * this.currentIndex}%)`
}
}
},
methods: {
selectTab(index) {
this.currentIndex = index
}
}
}
</script>
CSS样式实现
<style scoped>
.tab-container {
position: relative;
width: 100%;
}
.tab-header {
display: flex;
border-bottom: 1px solid #ddd;
}
.tab-header div {
flex: 1;
text-align: center;
padding: 10px;
cursor: pointer;
}
.tab-header div.active {
color: #42b983;
}
.tab-indicator {
position: absolute;
bottom: 0;
height: 2px;
background-color: #42b983;
transition: transform 0.3s ease;
}
.tab-content {
position: relative;
overflow: hidden;
height: 200px;
}
.tab-content div {
position: absolute;
width: 100%;
padding: 20px;
transition: transform 0.3s ease;
transform: translateX(-100%);
}
.tab-content div.active {
transform: translateX(0);
}
</style>
进阶优化方案
增加触摸滑动支持可以通过监听touchstart、touchmove和touchend事件来实现手势识别。计算滑动距离决定是否切换Tab。
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].clientX
},
handleTouchMove(e) {
this.moveX = e.touches[0].clientX
},
handleTouchEnd() {
const diff = this.moveX - this.startX
if (Math.abs(diff) > 50) {
if (diff > 0 && this.currentIndex > 0) {
this.currentIndex--
} else if (diff < 0 && this.currentIndex < this.tabs.length - 1) {
this.currentIndex++
}
}
}
}
响应式设计考虑
对于移动端适配,可以增加媒体查询调整Tab的样式:
@media (max-width: 768px) {
.tab-header div {
padding: 8px 5px;
font-size: 14px;
}
}






