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() {
const distance = this.endX - this.startX
if (Math.abs(distance) > 50) { // 滑动距离阈值
if (distance > 0) {
// 向右滑动逻辑
} else {
// 向左滑动逻辑
}
}
}
}
}
</script>
使用第三方库
可以使用 vue-touch 或 hammer.js 等库简化手势识别。以 hammer.js 为例:

import Hammer from 'hammerjs'
export default {
mounted() {
const hammer = new Hammer(this.$el)
hammer.on('swipeleft', () => {
// 向左滑动逻辑
})
hammer.on('swiperight', () => {
// 向右滑动逻辑
})
}
}
结合 CSS 过渡效果
为滑动切换添加平滑的过渡效果,可以通过 Vue 的过渡系统或 CSS 动画实现。

.slide-enter-active, .slide-leave-active {
transition: transform 0.5s ease;
}
.slide-enter {
transform: translateX(100%);
}
.slide-leave-to {
transform: translateX(-100%);
}
组件化实现
将滑动逻辑封装为可复用的组件,通过插槽或 props 传递内容。
<template>
<div class="swipe-container">
<div
class="swipe-content"
:style="{ transform: `translateX(${offset}px)` }"
>
<slot></slot>
</div>
</div>
</template>
响应式设计考虑
在移动端和桌面端都需要兼容滑动行为时,可以结合鼠标事件和触摸事件。
methods: {
handleStart(e) {
this.startX = e.type.includes('touch')
? e.touches[0].clientX
: e.clientX
}
}
通过以上方法可以实现基本的左右滑动切换功能,根据具体需求选择适合的实现方式。






