Vue 实现左右滑动
Vue 实现左右滑动的方法
使用 touch 事件监听
通过监听 touchstart、touchmove 和 touchend 事件实现基础滑动逻辑。在 Vue 组件中声明这些事件处理函数,计算滑动距离和方向。
export default {
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
// 根据 moveX 的值操作 DOM 元素
},
handleTouchEnd() {
if (Math.abs(this.moveX) > 50) {
// 触发滑动动作
}
this.startX = 0
this.moveX = 0
}
}
}
使用 CSS transform 实现动画效果
结合 CSS transform 属性实现平滑的滑动动画效果。通过动态绑定 style 或 class 控制元素位置。
<template>
<div
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
:style="{ transform: `translateX(${offsetX}px)` }"
>
<!-- 滑动内容 -->
</div>
</template>
使用第三方库
对于复杂滑动需求,可以使用专门为 Vue 设计的滑动组件库:
-
vue-swipe:轻量级触摸滑动组件

npm install vue-swipe --save -
Swiper.js:功能强大的滑动库,有官方 Vue 组件
npm install swiper@6.0.0 -
vue-awesome-swiper:Swiper 的 Vue 封装
npm install vue-awesome-swiper
实现分页指示器
为滑动内容添加分页指示器,增强用户体验。

<template>
<div class="slider-container">
<div class="slider" ref="slider">
<!-- 滑动内容 -->
</div>
<div class="pagination">
<span
v-for="(item, index) in items"
:class="{ active: currentIndex === index }"
@click="goTo(index)"
></span>
</div>
</div>
</template>
响应式处理
考虑不同设备的屏幕尺寸,使用 rem 或 vw 单位确保滑动距离适配各种屏幕。
.slider {
width: 100vw;
}
.slide-item {
width: 80vw;
margin: 0 10vw;
}
性能优化
对于大量滑动项,采用虚拟滚动技术优化性能。
export default {
data() {
return {
visibleItems: [],
allItems: [] // 大数据集
}
},
methods: {
updateVisibleItems() {
// 根据滑动位置计算可见项
}
}
}
边界处理
添加滑动边界检测,防止滑动超出内容范围。
handleTouchEnd() {
if (this.moveX > 100 && this.currentIndex > 0) {
this.currentIndex--
} else if (this.moveX < -100 && this.currentIndex < this.maxIndex) {
this.currentIndex++
}
this.resetPosition()
}






