vue 左右滑动实现
实现左右滑动的基本思路
在Vue中实现左右滑动效果,可以通过监听触摸事件(touchstart、touchmove、touchend)来计算滑动距离和方向。结合CSS的transform属性实现平滑的滑动动画效果。
使用原生事件监听实现
创建一个Vue组件,通过监听触摸事件来实现左右滑动:
<template>
<div
class="slider"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
>
<div
class="slider-content"
:style="{ transform: `translateX(${translateX}px)` }"
>
<!-- 滑动内容 -->
<div v-for="item in items" :key="item.id" class="slide">
{{ item.content }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, content: 'Slide 1' },
{ id: 2, content: 'Slide 2' },
{ id: 3, content: 'Slide 3' }
],
startX: 0,
translateX: 0,
currentIndex: 0
}
},
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].clientX
},
handleTouchMove(e) {
const currentX = e.touches[0].clientX
const diff = currentX - this.startX
this.translateX = diff
},
handleTouchEnd(e) {
const endX = e.changedTouches[0].clientX
const diff = endX - this.startX
// 滑动阈值,大于50px才切换
if (Math.abs(diff) > 50) {
if (diff > 0) {
// 向右滑动
this.currentIndex = Math.max(0, this.currentIndex - 1)
} else {
// 向左滑动
this.currentIndex = Math.min(this.items.length - 1, this.currentIndex + 1)
}
}
// 根据currentIndex计算最终位置
this.translateX = -this.currentIndex * this.$el.offsetWidth
}
}
}
</script>
<style>
.slider {
width: 100%;
overflow: hidden;
position: relative;
}
.slider-content {
display: flex;
transition: transform 0.3s ease;
}
.slide {
flex: 0 0 100%;
width: 100%;
}
</style>
使用第三方库实现
对于更复杂的需求,可以使用现成的Vue滑动组件库,如vue-awesome-swiper:
安装依赖:
npm install swiper vue-awesome-swiper
使用示例:
<template>
<swiper :options="swiperOptions">
<swiper-slide v-for="item in items" :key="item.id">
{{ item.content }}
</swiper-slide>
<div class="swiper-pagination" slot="pagination"></div>
</swiper>
</template>
<script>
import { Swiper, SwiperSlide } from 'vue-awesome-swiper'
import 'swiper/css/swiper.css'
export default {
components: {
Swiper,
SwiperSlide
},
data() {
return {
items: [
{ id: 1, content: 'Slide 1' },
{ id: 2, content: 'Slide 2' },
{ id: 3, content: 'Slide 3' }
],
swiperOptions: {
pagination: {
el: '.swiper-pagination'
},
// 可配置更多选项
loop: true,
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev'
}
}
}
}
}
</script>
性能优化建议
对于大量滑动项的情况,考虑实现虚拟滚动或懒加载。监听滑动位置,动态加载可见区域附近的内容,减少DOM节点数量。
添加防抖处理避免频繁触发滑动事件。在handleTouchMove方法中可以添加节流逻辑,限制事件触发频率。
handleTouchMove: _.throttle(function(e) {
const currentX = e.touches[0].clientX
const diff = currentX - this.startX
this.translateX = diff
}, 16) // 约60fps






