dom
<div @touchstart="moveStart" @touchmove="onMove" @touchend="moveEnd"></div>
js
data(){
return {
startX: 0, // 触摸起始x
startY: 0, // 触摸起始y
endX: 0, // 触摸结束x
endY: 0, // 触摸结束y
canMove: true, // 是否可以继续滑动
index: 0 // 控制滑动下标
}
}
methods(){
moveStart(e) {
this.startX = e.targetTouches[0].pageX
this.startY = e.targetTouches[0].pageY
},
onMove(e) {
this.endX = e.targetTouches[0].pageX
this.endY = e.targetTouches[0].pageY
const dValueX = Math.abs(this.startX - this.endX)
const dValueY = Math.abs(this.startY - this.endY)
if (dValueX > dValueY) {
// 水平滑动长度大于纵向滑动长度,那么选择水平滑动,阻止浏览器默认左右滑动事件
e.preventDefault()
if (dValueX > 40 && this.startX > this.endX) {
// 向左划
if (this.index < this.list.length - 1 && this.canMove) {
this.canMove = false
this.index += 1
}
} else if (dValueX > 40 && this.index > 0 && this.canMove) {
this.canMove = false
this.index -= 1
}
} else {
// 恢复默认事件
window.event.returnValue = true
}
},
moveEnd(e) {
this.canMove = true
this.startX = this.endX = 0
this.startY = this.endY = 0
},
}