vue怎么实现滑动
Vue 实现滑动效果的方法
使用 CSS 过渡动画
在 Vue 中可以通过 CSS 的 transition 或 animation 实现滑动效果。
<template>
<div class="slider" :style="{ transform: `translateX(${offset}px)` }"></div>
</template>
<script>
export default {
data() {
return {
offset: 0
}
},
methods: {
slide() {
this.offset += 100;
}
}
}
</script>
<style>
.slider {
transition: transform 0.3s ease;
}
</style>
使用第三方库
Vue 生态中有许多优秀的滑动组件库可供选择:
vue-awesome-swiper:基于 Swiper 的 Vue 封装vue-carousel:轻量级轮播组件v-touch:处理触摸事件实现滑动
npm install vue-awesome-swiper
<template>
<swiper>
<swiper-slide>Slide 1</swiper-slide>
<swiper-slide>Slide 2</swiper-slide>
</swiper>
</template>
<script>
import { Swiper, SwiperSlide } from 'vue-awesome-swiper'
import 'swiper/css/swiper.css'
export default {
components: {
Swiper,
SwiperSlide
}
}
</script>
手势滑动实现
通过监听 touch 事件实现自定义滑动逻辑:
<template>
<div
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
>
<!-- 滑动内容 -->
</div>
</template>
<script>
export default {
data() {
return {
startX: 0,
moveX: 0
}
},
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].clientX
},
handleTouchMove(e) {
this.moveX = e.touches[0].clientX - this.startX
},
handleTouchEnd() {
if (this.moveX > 50) {
// 向右滑动
} else if (this.moveX < -50) {
// 向左滑动
}
}
}
}
</script>
使用 Vue 动画组件
Vue 内置的 <transition> 组件可以实现元素进入/离开的滑动动画:

<template>
<button @click="show = !show">Toggle</button>
<transition name="slide">
<div v-if="show" class="box"></div>
</transition>
</template>
<style>
.slide-enter-active, .slide-leave-active {
transition: all 0.5s;
}
.slide-enter, .slide-leave-to {
transform: translateX(100px);
opacity: 0;
}
</style>
以上方法可以根据具体需求选择使用,CSS 过渡适合简单动画,第三方库适合复杂轮播效果,手势实现适合需要完全自定义的场景。






