vue实现swipe
Vue 实现 Swipe 功能的方法
使用第三方库 vue-awesome-swiper
vue-awesome-swiper 是基于 Swiper 的 Vue 封装,适合实现轮播、滑动等效果。
安装依赖:
npm install swiper vue-awesome-swiper
基本用法:

<template>
<swiper :options="swiperOption">
<swiper-slide v-for="(item, index) in slides" :key="index">
{{ item }}
</swiper-slide>
</swiper>
</template>
<script>
import { Swiper, SwiperSlide } from 'vue-awesome-swiper'
import 'swiper/css/swiper.css'
export default {
components: { Swiper, SwiperSlide },
data() {
return {
slides: ['Slide 1', 'Slide 2', 'Slide 3'],
swiperOption: {
autoplay: true,
loop: true
}
}
}
}
</script>
使用 Hammer.js 实现手势识别
Hammer.js 是专门处理手势的库,适合需要自定义滑动逻辑的场景。
安装依赖:

npm install hammerjs
示例实现:
<template>
<div ref="swipeContainer" class="swipe-container">
<div v-for="(item, index) in items" :key="index" class="slide">
{{ item }}
</div>
</div>
</template>
<script>
import Hammer from 'hammerjs'
export default {
data() {
return {
items: ['Item 1', 'Item 2', 'Item 3'],
currentIndex: 0
}
},
mounted() {
const hammer = new Hammer(this.$refs.swipeContainer)
hammer.on('swipeleft', this.nextSlide)
hammer.on('swiperight', this.prevSlide)
},
methods: {
nextSlide() {
this.currentIndex = Math.min(this.currentIndex + 1, this.items.length - 1)
},
prevSlide() {
this.currentIndex = Math.max(this.currentIndex - 1, 0)
}
}
}
</script>
<style>
.swipe-container {
overflow: hidden;
position: relative;
}
.slide {
width: 100%;
display: inline-block;
}
</style>
纯 CSS 实现简单滑动效果
对于简单需求,可以使用 CSS 的 transform 和 transition 属性。
<template>
<div class="swipe-wrapper">
<div
class="swipe-content"
:style="{ transform: `translateX(${-currentIndex * 100}%)` }"
>
<div v-for="(item, index) in items" :key="index" class="slide">
{{ item }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: ['Content 1', 'Content 2', 'Content 3'],
currentIndex: 0
}
},
methods: {
swipe(direction) {
if (direction === 'left') {
this.currentIndex = Math.min(this.currentIndex + 1, this.items.length - 1)
} else {
this.currentIndex = Math.max(this.currentIndex - 1, 0)
}
}
}
}
</script>
<style>
.swipe-wrapper {
overflow: hidden;
width: 100%;
}
.swipe-content {
display: flex;
transition: transform 0.3s ease;
}
.slide {
flex: 0 0 100%;
}
</style>
选择建议
- 需要完整轮播功能:推荐 vue-awesome-swiper
- 需要自定义手势交互:使用 Hammer.js
- 简单滑动效果:纯 CSS 实现即可
以上方法均可根据实际需求进行调整和扩展,vue-awesome-swiper 提供了最全面的功能选项,Hammer.js 适合需要精细控制手势的场景,而纯 CSS 方案则最为轻量。






