vue 左右滑动实现
实现 Vue 左右滑动的常见方法
监听触摸事件
通过 @touchstart、@touchmove 和 @touchend 监听手势,计算滑动距离和方向。适合自定义滑动逻辑,需手动处理边界条件和动画效果。
<template>
<div
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
>
<!-- 滑动内容 -->
</div>
</template>
<script>
export default {
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].clientX;
},
handleTouchMove(e) {
this.currentX = e.touches[0].clientX;
const diff = this.startX - this.currentX;
if (Math.abs(diff) > 5) { // 滑动阈值
this.isSwiping = true;
}
},
handleTouchEnd() {
if (this.isSwiping) {
// 处理滑动结束逻辑
}
}
}
};
</script>
使用 CSS 过渡或动画
结合 Vue 的 v-bind:style 或 v-bind:class 动态修改样式,通过 CSS 的 transform 和 transition 实现平滑滑动效果。
.swipe-container {
transition: transform 0.3s ease;
}
.swipe-left {
transform: translateX(-100px);
}
.swipe-right {
transform: translateX(100px);
}
<template>
<div
:class="{ 'swipe-left': isLeft, 'swipe-right': isRight }"
@click="handleSwipe"
>
<!-- 内容 -->
</div>
</template>
集成第三方库
使用现成的 Vue 滑动组件库(如 vue-touch、swiper-vue)快速实现功能,减少手动处理细节的工作量。
安装 Swiper:
npm install swiper vue-awesome-swiper
示例代码:
<template>
<swiper :options="swiperOptions">
<swiper-slide>Slide 1</swiper-slide>
<swiper-slide>Slide 2</swiper-slide>
</swiper>
</template>
<script>
import { Swiper, SwiperSlide } from 'vue-awesome-swiper';
export default {
components: { Swiper, SwiperSlide },
data() {
return {
swiperOptions: {
slidesPerView: 1,
spaceBetween: 30,
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev'
}
}
};
}
};
</script>
注意事项
- 性能优化:避免在
touchmove中频繁触发重排,可使用requestAnimationFrame。 - 移动端适配:注意
touch-actionCSS 属性,防止与浏览器默认行为冲突。 - 边界处理:滑动到首项或末项时禁止继续滑动,提供视觉反馈(如弹性动画)。







