vue实现swipe
Vue 实现 Swipe 功能
在 Vue 中实现 Swipe(滑动)功能可以通过多种方式实现,包括使用原生事件、第三方库或自定义指令。以下是几种常见的方法:
使用原生事件监听
通过监听 touchstart、touchmove 和 touchend 事件,可以实现基础的滑动功能。
<template>
<div
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
class="swipe-container"
>
<div class="content">滑动内容</div>
</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() {
if (this.startX - this.endX > 50) {
console.log('向左滑动');
} else if (this.endX - this.startX > 50) {
console.log('向右滑动');
}
},
},
};
</script>
<style>
.swipe-container {
width: 100%;
height: 200px;
background: #f0f0f0;
overflow: hidden;
}
</style>
使用第三方库(如 vue-swipe 或 swiper)
swiper 是一个流行的滑动库,支持 Vue 集成,功能强大且易于使用。
安装 swiper:

npm install swiper
在 Vue 中使用 swiper:
<template>
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide">Slide 1</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
</div>
</div>
</template>
<script>
import Swiper from 'swiper';
import 'swiper/swiper-bundle.css';
export default {
mounted() {
new Swiper('.swiper-container', {
loop: true,
autoplay: {
delay: 3000,
},
});
},
};
</script>
<style>
.swiper-container {
width: 100%;
height: 300px;
}
.swiper-slide {
background: #ccc;
display: flex;
justify-content: center;
align-items: center;
}
</style>
使用 Vue 指令实现自定义滑动
可以通过自定义指令封装滑动逻辑,方便复用。

<template>
<div v-swipe="handleSwipe" class="swipe-area">
滑动区域
</div>
</template>
<script>
export default {
directives: {
swipe: {
bind(el, binding) {
let startX = 0;
let endX = 0;
el.addEventListener('touchstart', (e) => {
startX = e.touches[0].clientX;
});
el.addEventListener('touchmove', (e) => {
endX = e.touches[0].clientX;
});
el.addEventListener('touchend', () => {
if (startX - endX > 50) {
binding.value('left');
} else if (endX - startX > 50) {
binding.value('right');
}
});
},
},
},
methods: {
handleSwipe(direction) {
console.log(`滑动方向:${direction}`);
},
},
};
</script>
<style>
.swipe-area {
width: 100%;
height: 200px;
background: #e0e0e0;
display: flex;
justify-content: center;
align-items: center;
}
</style>
使用 vue-touch 库
vue-touch 是一个专门为 Vue 设计的触摸事件库,支持滑动、点击等手势。
安装 vue-touch:
npm install vue-touch@next
在 Vue 中使用 vue-touch:
<template>
<v-touch @swipeleft="onSwipeLeft" @swiperight="onSwipeRight">
<div class="swipe-box">滑动区域</div>
</v-touch>
</template>
<script>
import { VueTouch } from 'vue-touch';
export default {
components: {
'v-touch': VueTouch,
},
methods: {
onSwipeLeft() {
console.log('向左滑动');
},
onSwipeRight() {
console.log('向右滑动');
},
},
};
</script>
<style>
.swipe-box {
width: 100%;
height: 200px;
background: #ddd;
display: flex;
justify-content: center;
align-items: center;
}
</style>
总结
- 原生事件:适合简单滑动需求,但需要手动处理事件逻辑。
- 第三方库(如
swiper):功能强大,适合复杂滑动场景(如轮播图)。 - 自定义指令:可复用性强,适合封装通用滑动逻辑。
vue-touch:专门为 Vue 设计,简化手势事件处理。






