vue实现左右滑动组件
Vue 实现左右滑动组件
方案一:基于 touch 事件实现
监听 touchstart、touchmove 和 touchend 事件,计算滑动距离和方向:

<template>
<div
class="slider"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
>
<div class="slider-content" :style="contentStyle">
<slot></slot>
</div>
</div>
</template>
<script>
export default {
data() {
return {
startX: 0,
moveX: 0,
currentTranslate: 0,
isDragging: false
}
},
computed: {
contentStyle() {
return {
transform: `translateX(${this.currentTranslate}px)`,
transition: this.isDragging ? 'none' : 'transform 0.3s ease'
}
}
},
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].clientX
this.isDragging = true
},
handleTouchMove(e) {
if (!this.isDragging) return
this.moveX = e.touches[0].clientX - this.startX
this.currentTranslate += this.moveX
this.startX = e.touches[0].clientX
},
handleTouchEnd() {
this.isDragging = false
// 这里可以添加滑动结束后的逻辑,如自动对齐到最近的item
}
}
}
</script>
<style>
.slider {
overflow: hidden;
position: relative;
}
.slider-content {
display: flex;
will-change: transform;
}
</style>
方案二:使用第三方库 vue-awesome-swiper
安装 Swiper 库:

npm install swiper vue-awesome-swiper
组件实现:
<template>
<swiper :options="swiperOption">
<swiper-slide v-for="(item, index) in items" :key="index">
<!-- 幻灯片内容 -->
</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: [/* 你的数据 */],
swiperOption: {
pagination: {
el: '.swiper-pagination'
},
slidesPerView: 'auto',
spaceBetween: 20,
freeMode: true
}
}
}
}
</script>
方案三:基于 CSS Scroll Snap
纯 CSS 方案,现代浏览器支持:
<template>
<div class="scroll-container">
<div class="scroll-content">
<div v-for="(item, index) in items" :key="index" class="scroll-item">
<!-- 项目内容 -->
</div>
</div>
</div>
</template>
<style>
.scroll-container {
width: 100%;
overflow-x: auto;
scroll-snap-type: x mandatory;
-webkit-overflow-scrolling: touch; /* iOS平滑滚动 */
}
.scroll-content {
display: flex;
width: max-content;
}
.scroll-item {
scroll-snap-align: start;
flex: 0 0 auto;
width: 80vw; /* 根据需要调整 */
margin-right: 10px;
}
</style>
性能优化建议
- 使用
will-change: transform提升动画性能 - 对于大量项目,考虑虚拟滚动技术
- 移动端确保添加
-webkit-overflow-scrolling: touch属性 - 避免在滑动过程中频繁触发重绘操作
注意事项
- 触摸事件方案需要考虑边界情况处理
- 第三方库方案功能更全面但会增加包体积
- CSS Scroll Snap 方案最简单但兼容性稍差
- 根据项目需求选择合适的技术方案






