Vue实现移动端上滑动
Vue 实现移动端滑动功能
使用 touch 事件实现滑动
监听 touchstart、touchmove 和 touchend 事件来实现滑动效果。通过计算触摸点的位移来判断滑动方向和距离。
<template>
<div
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
class="swipe-container"
>
<!-- 滑动内容 -->
</div>
</template>
<script>
export default {
data() {
return {
startX: 0,
startY: 0,
moveX: 0,
moveY: 0
}
},
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].clientX
this.startY = e.touches[0].clientY
},
handleTouchMove(e) {
this.moveX = e.touches[0].clientX - this.startX
this.moveY = e.touches[0].clientY - this.startY
// 判断滑动方向
if (Math.abs(this.moveX) > Math.abs(this.moveY)) {
// 水平滑动
} else {
// 垂直滑动
}
},
handleTouchEnd() {
// 滑动结束处理
}
}
}
</script>
使用 CSS transform 实现平滑滑动
结合 CSS transform 属性实现流畅的滑动动画效果。
methods: {
handleTouchMove(e) {
// 计算位移
const deltaX = e.touches[0].clientX - this.startX
const deltaY = e.touches[0].clientY - this.startY
// 应用transform
this.$refs.container.style.transform = `translate3d(${deltaX}px, ${deltaY}px, 0)`
},
handleTouchEnd() {
// 滑动结束恢复位置或继续动画
this.$refs.container.style.transition = 'transform 0.3s ease'
this.$refs.container.style.transform = 'translate3d(0, 0, 0)'
}
}
使用第三方库实现复杂滑动
对于更复杂的滑动需求,可以使用第三方库如 hammer.js 或 vue-touch。

安装 hammer.js:
npm install hammerjs
使用示例:

import Hammer from 'hammerjs'
export default {
mounted() {
const hammer = new Hammer(this.$el)
hammer.on('swipeleft', () => {
// 左滑处理
})
hammer.on('swiperight', () => {
// 右滑处理
})
hammer.on('swipeup', () => {
// 上滑处理
})
hammer.on('swipedown', () => {
// 下滑处理
})
}
}
实现惯性滑动效果
通过计算滑动速度和方向,添加惯性滑动效果。
handleTouchEnd() {
const velocity = Math.sqrt(this.moveX * this.moveX + this.moveY * this.moveY) / 100
const directionX = this.moveX > 0 ? 1 : -1
const directionY = this.moveY > 0 ? 1 : -1
// 应用惯性滑动
this.$refs.container.style.transition = 'transform 0.5s cubic-bezier(0.1, 0.7, 0.1, 1)'
this.$refs.container.style.transform = `
translate3d(${directionX * velocity * 100}px, ${directionY * velocity * 100}px, 0)
`
// 恢复原位
setTimeout(() => {
this.$refs.container.style.transition = 'transform 0.3s ease'
this.$refs.container.style.transform = 'translate3d(0, 0, 0)'
}, 500)
}
性能优化建议
使用 transform 和 will-change 属性提升滑动性能:
.swipe-container {
will-change: transform;
transform: translate3d(0, 0, 0);
}
避免在 touchmove 事件中执行复杂计算,防止卡顿。使用 requestAnimationFrame 优化动画:
handleTouchMove(e) {
requestAnimationFrame(() => {
// 滑动处理逻辑
})
}






