vue实现滑动翻页
Vue 实现滑动翻页方案
监听触摸事件
通过 @touchstart、@touchmove 和 @touchend 监听手势,记录滑动起始位置和偏移量:
data() {
return {
startX: 0,
moveX: 0
}
},
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].clientX
},
handleTouchMove(e) {
this.moveX = e.touches[0].clientX - this.startX
},
handleTouchEnd() {
if (Math.abs(this.moveX) > 50) { // 滑动阈值
this.moveX > 0 ? this.prevPage() : this.nextPage()
}
this.moveX = 0
}
}
绑定事件到容器
在模板中为滑动区域添加事件绑定:
<div
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
class="swipe-container"
>
<!-- 翻页内容 -->
</div>
添加过渡动画
使用 Vue 的 <transition> 组件实现平滑翻页效果:
<transition :name="transitionName">
<div :key="currentPage">
<!-- 当前页内容 -->
</div>
</transition>
.slide-left-enter-active,
.slide-left-leave-active {
transition: transform 0.3s ease;
}
.slide-left-enter {
transform: translateX(100%);
}
.slide-left-leave-to {
transform: translateX(-100%);
}
/* 反向滑动样式同理 */
分页控制逻辑
维护当前页码并限制边界:
data() {
return {
currentPage: 1,
totalPages: 5
}
},
methods: {
nextPage() {
if (this.currentPage < this.totalPages) {
this.transitionName = 'slide-left'
this.currentPage++
}
},
prevPage() {
if (this.currentPage > 1) {
this.transitionName = 'slide-right'
this.currentPage--
}
}
}
优化建议

- 添加
touch-action: pan-yCSS 属性避免浏览器默认行为冲突 - 使用
requestAnimationFrame优化滑动性能 - 移动端适配需考虑
passive: true事件选项提升滚动性能






