vue实现app滑动
Vue 实现移动端滑动效果
使用 Vue 实现移动端滑动效果可以通过以下几种方式实现:
1. 使用 touch 事件监听
通过监听 touchstart、touchmove 和 touchend 事件,计算滑动距离和方向。

<template>
<div
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
style="width: 100%; height: 100vh;"
>
<!-- 滑动内容 -->
</div>
</template>
<script>
export default {
data() {
return {
startX: 0,
startY: 0,
endX: 0,
endY: 0
}
},
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].clientX
this.startY = e.touches[0].clientY
},
handleTouchMove(e) {
this.endX = e.touches[0].clientX
this.endY = e.touches[0].clientY
},
handleTouchEnd() {
const diffX = this.endX - this.startX
const diffY = this.endY - this.startY
if (Math.abs(diffX) > Math.abs(diffY)) {
// 水平滑动
if (diffX > 0) {
console.log('向右滑动')
} else {
console.log('向左滑动')
}
} else {
// 垂直滑动
if (diffY > 0) {
console.log('向下滑动')
} else {
console.log('向上滑动')
}
}
}
}
}
</script>
2. 使用第三方库
推荐使用 vue-touch 或 hammer.js 等库简化手势识别。

// 安装 hammer.js
npm install hammerjs
// 在组件中使用
import Hammer from 'hammerjs'
export default {
mounted() {
const element = this.$el
const hammer = new Hammer(element)
hammer.on('swipeleft', () => {
console.log('向左滑动')
})
hammer.on('swiperight', () => {
console.log('向右滑动')
})
}
}
3. 使用 CSS 过渡动画 结合 Vue 的过渡系统实现平滑滑动效果。
<template>
<transition name="slide">
<div v-if="show" class="slider">
<!-- 滑动内容 -->
</div>
</transition>
</template>
<style>
.slide-enter-active, .slide-leave-active {
transition: transform 0.5s;
}
.slide-enter {
transform: translateX(100%);
}
.slide-leave-to {
transform: translateX(-100%);
}
</style>
4. 实现轮播图效果 结合 Vue 的响应式数据和 CSS 实现轮播滑动。
<template>
<div class="carousel" @touchstart="startDrag" @touchmove="onDrag" @touchend="endDrag">
<div
class="slide"
v-for="(item, index) in slides"
:key="index"
:style="{ transform: `translateX(${currentIndex * -100}%)` }"
>
{{ item }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
slides: ['Slide 1', 'Slide 2', 'Slide 3'],
currentIndex: 0,
startX: 0
}
},
methods: {
startDrag(e) {
this.startX = e.touches[0].clientX
},
onDrag(e) {
const x = e.touches[0].clientX
const diff = this.startX - x
if (Math.abs(diff) > 50) {
if (diff > 0) {
this.next()
} else {
this.prev()
}
}
},
endDrag() {
this.startX = 0
},
next() {
this.currentIndex = (this.currentIndex + 1) % this.slides.length
},
prev() {
this.currentIndex = (this.currentIndex - 1 + this.slides.length) % this.slides.length
}
}
}
</script>
<style>
.carousel {
overflow: hidden;
position: relative;
width: 100%;
height: 200px;
}
.slide {
position: absolute;
width: 100%;
height: 100%;
transition: transform 0.3s ease;
}
</style>
性能优化建议
- 使用
transform代替left/top进行动画,避免重排 - 添加
will-change: transform提示浏览器优化 - 对于复杂滑动效果,考虑使用
requestAnimationFrame - 在移动端注意 300ms 点击延迟问题,可添加
touch-actionCSS 属性
兼容性处理
- 添加 passive event listeners 提高滚动性能
- 注意 iOS 的橡皮筋效果可能干扰滑动逻辑
- 针对不同设备像素比调整滑动阈值
以上方法可以根据具体需求组合使用,实现各种滑动交互效果。






