vue实现触摸轮播
Vue 实现触摸轮播
使用第三方库(如 Swiper)
安装 Swiper 库:
npm install swiper
在 Vue 组件中引入 Swiper:
<template>
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide" v-for="(item, index) in slides" :key="index">
{{ item }}
</div>
</div>
</div>
</template>
<script>
import Swiper from 'swiper';
import 'swiper/css/swiper.css';
export default {
data() {
return {
slides: ['Slide 1', 'Slide 2', 'Slide 3']
};
},
mounted() {
new Swiper('.swiper-container', {
loop: true,
pagination: {
el: '.swiper-pagination',
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
touchEventsTarget: 'container',
touchRatio: 1,
touchAngle: 45,
simulateTouch: true
});
}
};
</script>
自定义触摸事件实现
通过 Vue 的 @touchstart、@touchmove 和 @touchend 事件实现基础触摸轮播:
<template>
<div
class="carousel"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
>
<div
class="slide-container"
:style="{ transform: `translateX(${offsetX}px)` }"
>
<div v-for="(item, index) in slides" :key="index" class="slide">
{{ item }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
slides: ['Slide 1', 'Slide 2', 'Slide 3'],
currentIndex: 0,
offsetX: 0,
startX: 0,
moveX: 0
};
},
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].clientX;
},
handleTouchMove(e) {
this.moveX = e.touches[0].clientX - this.startX;
this.offsetX = this.moveX;
},
handleTouchEnd() {
const threshold = 50;
if (Math.abs(this.moveX) > threshold) {
if (this.moveX > 0) {
this.currentIndex = Math.max(0, this.currentIndex - 1);
} else {
this.currentIndex = Math.min(this.slides.length - 1, this.currentIndex + 1);
}
}
this.offsetX = -this.currentIndex * 100;
this.moveX = 0;
}
}
};
</script>
<style>
.carousel {
overflow: hidden;
position: relative;
width: 100%;
}
.slide-container {
display: flex;
transition: transform 0.3s ease;
}
.slide {
flex: 0 0 100%;
width: 100%;
}
</style>
优化触摸体验
添加过渡动画和边界检测:
methods: {
handleTouchEnd() {
const threshold = 50;
if (Math.abs(this.moveX) > threshold) {
if (this.moveX > 0 && this.currentIndex > 0) {
this.currentIndex--;
} else if (this.moveX < 0 && this.currentIndex < this.slides.length - 1) {
this.currentIndex++;
}
}
this.animateSlide();
},
animateSlide() {
const targetX = -this.currentIndex * 100;
const distance = targetX - this.offsetX;
const duration = 300;
const startTime = performance.now();
const animate = (currentTime) => {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
this.offsetX = this.offsetX + distance * progress;
if (progress < 1) {
requestAnimationFrame(animate);
}
};
requestAnimationFrame(animate);
}
}
注意事项
- 移动端开发需添加
meta标签禁用默认手势:<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> - 对于更复杂的需求(如无限循环、垂直滑动),推荐直接使用 Swiper 等成熟库。
- 自定义实现时注意处理快速滑动和边缘情况。







