vue实现左右滑动
Vue 实现左右滑动效果
使用 touch 事件实现基础滑动
监听 touchstart、touchmove 和 touchend 事件实现基础滑动逻辑:
<template>
<div
class="slider"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
>
<div class="slider-content" :style="contentStyle">
<!-- 滑动内容 -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
startX: 0,
moveX: 0,
offsetX: 0,
isDragging: false
}
},
computed: {
contentStyle() {
return {
transform: `translateX(${this.offsetX}px)`,
transition: this.isDragging ? 'none' : 'transform 0.3s ease'
}
}
},
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].clientX
this.isDragging = true
},
handleTouchMove(e) {
this.moveX = e.touches[0].clientX
this.offsetX = this.moveX - this.startX
},
handleTouchEnd() {
this.isDragging = false
// 添加边界判断和回弹逻辑
}
}
}
</script>
使用 CSS Scroll Snap
结合 CSS 的 scroll-snap 特性实现更流畅的滑动体验:

.slider-container {
overflow-x: auto;
scroll-snap-type: x mandatory;
-webkit-overflow-scrolling: touch;
}
.slide-item {
scroll-snap-align: start;
flex: 0 0 auto;
}
使用第三方库
对于更复杂的需求,可以使用专门的滑动库:
- Swiper Vue:
npm install swiper@latest
<template>
<swiper
:slides-per-view="1"
:space-between="50"
@swiper="onSwiper"
@slideChange="onSlideChange"
>
<swiper-slide>Slide 1</swiper-slide>
<swiper-slide>Slide 2</swiper-slide>
</swiper>
</template>
<script>
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/css'
export default {
components: {
Swiper,
SwiperSlide
}
}
</script>
- Vue-Awesome-Swiper:
npm install vue-awesome-swiper@4.1.1
性能优化技巧
添加 will-change 属性提升动画性能:

.slider-content {
will-change: transform;
}
使用 requestAnimationFrame 优化 touchmove 事件:
let animationId = null
handleTouchMove(e) {
const update = () => {
this.moveX = e.touches[0].clientX
this.offsetX = this.moveX - this.startX
animationId = requestAnimationFrame(update)
}
cancelAnimationFrame(animationId)
animationId = requestAnimationFrame(update)
}
边界处理
添加滑动边界判断防止过度滑动:
handleTouchEnd() {
const maxOffset = window.innerWidth * 0.3
if (Math.abs(this.offsetX) > maxOffset) {
// 执行翻页逻辑
} else {
// 回弹到原位置
this.offsetX = 0
}
}






