touchmove实现左右滑动vue
在 Vue 中实现左右滑动效果可以通过监听 touchstart、touchmove 和 touchend 事件来实现。以下是具体实现方法:
监听触摸事件
在 Vue 组件的模板中,为需要滑动的元素绑定触摸事件:

<template>
<div
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
class="slider-container"
>
<!-- 滑动内容 -->
</div>
</template>
记录触摸起始位置
在组件的 data 或 setup 中定义变量来记录触摸的起始位置:

data() {
return {
touchStartX: 0,
touchEndX: 0
}
}
实现触摸事件处理函数
methods: {
handleTouchStart(event) {
this.touchStartX = event.touches[0].clientX
},
handleTouchMove(event) {
this.touchEndX = event.touches[0].clientX
// 可以在这里添加实时滑动效果
},
handleTouchEnd() {
const threshold = 50 // 滑动阈值
const distance = this.touchEndX - this.touchStartX
if (Math.abs(distance) > threshold) {
if (distance > 0) {
// 向右滑动
this.$emit('swipe-right')
} else {
// 向左滑动
this.$emit('swipe-left')
}
}
}
}
添加滑动动画效果
可以为滑动元素添加 CSS 过渡效果:
.slider-container {
transition: transform 0.3s ease;
}
实时滑动反馈
如果需要实时跟随手指移动,可以在 handleTouchMove 中更新元素位置:
handleTouchMove(event) {
this.touchEndX = event.touches[0].clientX
const distance = this.touchEndX - this.touchStartX
this.$refs.slider.style.transform = `translateX(${distance}px)`
}
完整示例
<template>
<div
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
class="slider-container"
ref="slider"
>
<slot></slot>
</div>
</template>
<script>
export default {
data() {
return {
touchStartX: 0,
touchEndX: 0
}
},
methods: {
handleTouchStart(event) {
this.touchStartX = event.touches[0].clientX
},
handleTouchMove(event) {
this.touchEndX = event.touches[0].clientX
const distance = this.touchEndX - this.touchStartX
this.$refs.slider.style.transform = `translateX(${distance}px)`
},
handleTouchEnd() {
const threshold = 50
const distance = this.touchEndX - this.touchStartX
if (Math.abs(distance) > threshold) {
if (distance > 0) {
this.$emit('swipe-right')
} else {
this.$emit('swipe-left')
}
}
this.$refs.slider.style.transform = 'translateX(0)'
}
}
}
</script>
<style>
.slider-container {
transition: transform 0.3s ease;
}
</style>
这种方法实现了基本的左右滑动检测功能,可以根据需要扩展更复杂的滑动效果和交互。






