touchmove实现左右滑动vue
实现左右滑动的 Vue 方法
使用 touchmove 事件监听
在 Vue 中监听 touchstart、touchmove 和 touchend 事件,通过计算触摸点的位移差实现左右滑动判断。
<template>
<div
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
style="width: 100%; height: 200px; background: #eee;"
>
{{ swipeDirection }}
</div>
</template>
<script>
export default {
data() {
return {
startX: 0,
endX: 0,
swipeDirection: ''
};
},
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].clientX;
},
handleTouchMove(e) {
this.endX = e.touches[0].clientX;
},
handleTouchEnd() {
const diff = this.endX - this.startX;
if (Math.abs(diff) > 50) { // 阈值设为50px
this.swipeDirection = diff > 0 ? '右滑' : '左滑';
}
}
}
};
</script>
结合 CSS 过渡效果
为滑动添加平滑动画效果,通过动态绑定 transform 属性。
<template>
<div
@touchstart="startDrag"
@touchmove="onDrag"
@touchend="endDrag"
:style="{ transform: `translateX(${offsetX}px)` }"
style="transition: transform 0.3s; width: 100%; height: 200px;"
>
滑动内容
</div>
</template>
<script>
export default {
data() {
return {
startX: 0,
offsetX: 0,
isDragging: false
};
},
methods: {
startDrag(e) {
this.startX = e.touches[0].clientX;
this.isDragging = true;
},
onDrag(e) {
if (!this.isDragging) return;
this.offsetX = e.touches[0].clientX - this.startX;
},
endDrag() {
this.isDragging = false;
// 根据滑动距离决定最终位置(如归零或切换到下一页)
this.offsetX = 0;
}
}
};
</script>
使用第三方库
集成 vue-touch 或 hammer.js 简化手势识别。
安装 hammer.js:
npm install hammerjs
示例代码:
import Hammer from 'hammerjs';
export default {
mounted() {
const hammer = new Hammer(this.$el);
hammer.on('swipeleft', () => {
console.log('左滑触发');
});
hammer.on('swiperight', () => {
console.log('右滑触发');
});
}
};
注意事项
- 性能优化:避免在
touchmove中执行复杂计算,必要时使用requestAnimationFrame。 - 边界处理:限制滑动范围,防止内容滑出可视区域。
- 移动端适配:添加
touch-action: pan-yCSS 属性防止默认滚动行为干扰。 - 阈值判断:根据实际需求调整滑动距离阈值(如示例中的50px)。







