vue实现滑动翻页功能
实现滑动翻页的基本思路
滑动翻页功能通常结合触摸事件(touchstart、touchmove、touchend)或第三方库(如hammer.js)实现。核心逻辑是通过计算滑动距离和方向,触发页面切换。
使用原生触摸事件实现
-
监听触摸事件
在Vue组件的mounted钩子中绑定事件,记录触摸起始位置:mounted() { this.$el.addEventListener('touchstart', this.handleTouchStart, { passive: false }); this.$el.addEventListener('touchmove', this.handleTouchMove, { passive: false }); this.$el.addEventListener('touchend', this.handleTouchEnd); } -
处理触摸逻辑
定义触摸事件处理方法,计算滑动方向和距离:
methods: { handleTouchStart(e) { this.startX = e.touches[0].clientX; this.startY = e.touches[0].clientY; }, handleTouchMove(e) { if (!this.startX) return; const currentX = e.touches[0].clientX; const diffX = this.startX - currentX; // 阻止垂直滚动误触 if (Math.abs(diffX) < Math.abs(this.startY - e.touches[0].clientY)) return; e.preventDefault(); this.$refs.content.style.transform = `translateX(-${diffX}px)`; }, handleTouchEnd(e) { if (!this.startX) return; const endX = e.changedTouches[0].clientX; const diffX = this.startX - endX; // 滑动距离超过阈值则翻页 if (Math.abs(diffX) > 50) { this.currentPage += diffX > 0 ? 1 : -1; } this.$refs.content.style.transform = ''; this.startX = null; } }
使用第三方库(hammer.js)
-
安装hammer.js
通过npm安装依赖:npm install hammerjs -
封装手势指令
创建自定义指令处理滑动手势:
import Hammer from 'hammerjs'; Vue.directive('swipe', { inserted(el, binding) { const mc = new Hammer(el); mc.on('swipeleft', () => binding.value('left')); mc.on('swiperight', () => binding.value('right')); } }); -
组件中使用指令
在模板中绑定指令和翻页逻辑:<template> <div v-swipe="handleSwipe"> <!-- 页面内容 --> </div> </template> <script> export default { methods: { handleSwipe(direction) { this.currentPage += direction === 'left' ? 1 : -1; } } } </script>
结合过渡动画
添加Vue的过渡效果提升用户体验:
<template>
<transition name="slide">
<div :key="currentPage">
<!-- 当前页内容 -->
</div>
</transition>
</template>
<style>
.slide-enter-active, .slide-leave-active {
transition: transform 0.3s ease;
}
.slide-enter {
transform: translateX(100%);
}
.slide-leave-to {
transform: translateX(-100%);
}
</style>
注意事项
- 边界处理:翻页时需检查
currentPage是否超出总页数范围。 - 性能优化:对于复杂内容,可使用
<keep-alive>缓存页面。 - 移动端适配:建议通过CSS的
touch-action: pan-y限制垂直滚动干扰。
以上方法可根据实际需求选择原生实现或库集成,后者代码更简洁但会增加依赖体积。






