vue实现滑动翻页
Vue 实现滑动翻页的方法
使用 Touch 事件监听
在 Vue 中可以通过监听 touchstart、touchmove 和 touchend 事件来实现滑动翻页效果。需要在组件中定义相关的事件处理函数。
<template>
<div
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
>
<!-- 页面内容 -->
</div>
</template>
<script>
export default {
data() {
return {
startX: 0,
endX: 0
}
},
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].clientX
},
handleTouchMove(e) {
this.endX = e.touches[0].clientX
},
handleTouchEnd() {
if (this.startX - this.endX > 50) {
// 向左滑动,下一页
this.nextPage()
} else if (this.endX - this.startX > 50) {
// 向右滑动,上一页
this.prevPage()
}
},
nextPage() {
// 翻页逻辑
},
prevPage() {
// 翻页逻辑
}
}
}
</script>
使用第三方库
可以使用现成的 Vue 滑动组件库如 vue-touch 或 hammer.js 来实现更复杂的滑动效果。
安装 hammer.js:

npm install hammerjs
在 Vue 中使用:
import Hammer from 'hammerjs'
export default {
mounted() {
const hammer = new Hammer(this.$el)
hammer.on('swipeleft', this.nextPage)
hammer.on('swiperight', this.prevPage)
},
methods: {
nextPage() {
// 下一页逻辑
},
prevPage() {
// 上一页逻辑
}
}
}
CSS 过渡动画
为滑动翻页添加平滑的过渡效果,可以使用 CSS 的 transition 和 transform 属性。

.page-container {
transition: transform 0.3s ease;
}
.page-slide-left {
transform: translateX(-100%);
}
.page-slide-right {
transform: translateX(100%);
}
在 Vue 中动态切换类名:
<template>
<div
class="page-container"
:class="{ 'page-slide-left': isSlidingLeft, 'page-slide-right': isSlidingRight }"
>
<!-- 页面内容 -->
</div>
</template>
<script>
export default {
data() {
return {
isSlidingLeft: false,
isSlidingRight: false
}
},
methods: {
nextPage() {
this.isSlidingLeft = true
setTimeout(() => {
// 实际翻页逻辑
this.isSlidingLeft = false
}, 300)
},
prevPage() {
this.isSlidingRight = true
setTimeout(() => {
// 实际翻页逻辑
this.isSlidingRight = false
}, 300)
}
}
}
</script>
使用 Vue 过渡组件
Vue 提供了内置的 <transition> 组件,可以用来实现更复杂的页面切换动画。
<template>
<transition name="slide">
<div v-if="currentPage === 1">Page 1</div>
<div v-else-if="currentPage === 2">Page 2</div>
</transition>
</template>
<style>
.slide-enter-active, .slide-leave-active {
transition: transform 0.5s;
}
.slide-enter {
transform: translateX(100%);
}
.slide-leave-to {
transform: translateX(-100%);
}
</style>






