vue实现swipe
Vue 实现 Swipe 功能
使用第三方库(如 vue-awesome-swiper)
安装 vue-awesome-swiper 库:
npm install swiper vue-awesome-swiper --save
在组件中引入并使用:

<template>
<swiper :options="swiperOption">
<swiper-slide>Slide 1</swiper-slide>
<swiper-slide>Slide 2</swiper-slide>
<swiper-slide>Slide 3</swiper-slide>
</swiper>
</template>
<script>
import { Swiper, SwiperSlide } from 'vue-awesome-swiper'
import 'swiper/css/swiper.css'
export default {
components: {
Swiper,
SwiperSlide
},
data() {
return {
swiperOption: {
autoplay: true,
loop: true
}
}
}
}
</script>
自定义实现 Swipe
监听触摸事件实现基本滑动功能:

<template>
<div
class="swipe-container"
@touchstart="onTouchStart"
@touchmove="onTouchMove"
@touchend="onTouchEnd"
>
<div class="swipe-content" :style="contentStyle">
<div v-for="(item, index) in items" :key="index" class="slide">
{{ item }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: ['Slide 1', 'Slide 2', 'Slide 3'],
startX: 0,
currentX: 0,
isDragging: false,
currentIndex: 0
}
},
computed: {
contentStyle() {
return {
transform: `translateX(${-this.currentIndex * 100 + this.currentX}px)`,
transition: this.isDragging ? 'none' : 'transform 0.3s ease'
}
}
},
methods: {
onTouchStart(e) {
this.startX = e.touches[0].clientX
this.isDragging = true
},
onTouchMove(e) {
if (!this.isDragging) return
this.currentX = e.touches[0].clientX - this.startX
},
onTouchEnd() {
this.isDragging = false
const threshold = 50
if (this.currentX > threshold && this.currentIndex > 0) {
this.currentIndex--
} else if (this.currentX < -threshold && this.currentIndex < this.items.length - 1) {
this.currentIndex++
}
this.currentX = 0
}
}
}
</script>
<style>
.swipe-container {
overflow: hidden;
position: relative;
width: 100%;
}
.swipe-content {
display: flex;
width: 100%;
}
.slide {
flex: 0 0 100%;
min-height: 200px;
display: flex;
align-items: center;
justify-content: center;
background: #eee;
border: 1px solid #ddd;
}
</style>
使用 Vue 手势库(如 vue-touch)
安装 vue-touch:
npm install vue-touch@next --save
注册插件并使用:
<template>
<v-touch @swipeleft="onSwipeLeft" @swiperight="onSwipeRight">
<div class="swipe-content">
<div v-show="currentIndex === 0">Slide 1</div>
<div v-show="currentIndex === 1">Slide 2</div>
<div v-show="currentIndex === 2">Slide 3</div>
</div>
</v-touch>
</template>
<script>
import VueTouch from 'vue-touch'
import Vue from 'vue'
Vue.use(VueTouch)
export default {
data() {
return {
currentIndex: 0
}
},
methods: {
onSwipeLeft() {
if (this.currentIndex < 2) {
this.currentIndex++
}
},
onSwipeRight() {
if (this.currentIndex > 0) {
this.currentIndex--
}
}
}
}
</script>






