vue怎么实现滑动
Vue 实现滑动效果的方法
使用原生 CSS 实现滑动
通过 CSS 的 transition 或 transform 属性实现基础滑动效果。适用于简单的元素移动需求。
<template>
<div class="slider" @click="toggleSlide">
<div class="slide-content" :class="{ 'active': isActive }">
滑动内容
</div>
</div>
</template>
<script>
export default {
data() {
return {
isActive: false
};
},
methods: {
toggleSlide() {
this.isActive = !this.isActive;
}
}
};
</script>
<style>
.slide-content {
transition: transform 0.3s ease;
transform: translateX(-100%);
}
.slide-content.active {
transform: translateX(0);
}
</style>
使用第三方库(如 Swiper)
对于复杂的滑动需求(如轮播图),推荐使用 Swiper.js。需先安装依赖:
npm install swiper
示例代码:
<template>
<swiper :options="swiperOptions">
<swiper-slide v-for="(item, index) in slides" :key="index">
{{ item }}
</swiper-slide>
</swiper>
</template>
<script>
import { Swiper, SwiperSlide } from 'swiper/vue';
import 'swiper/swiper-bundle.css';
export default {
components: { Swiper, SwiperSlide },
data() {
return {
slides: ['Slide 1', 'Slide 2', 'Slide 3'],
swiperOptions: {
loop: true,
pagination: { el: '.swiper-pagination' }
}
};
}
};
</script>
手势滑动(如 Hammer.js)
实现手势控制的滑动效果,需安装 Hammer.js:
npm install hammerjs
示例代码:
<template>
<div ref="slider" class="slider">
滑动区域
</div>
</template>
<script>
import Hammer from 'hammerjs';
export default {
mounted() {
const slider = this.$refs.slider;
const hammer = new Hammer(slider);
hammer.on('swipeleft', () => console.log('向左滑动'));
hammer.on('swiperight', () => console.log('向右滑动'));
}
};
</script>
移动端优化(touch 事件)
针对移动端自定义滑动逻辑,监听 touchstart、touchmove、touchend 事件:

<template>
<div
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
>
滑动内容
</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>
注意事项
- 性能优化:避免在
touchmove中执行复杂计算,防止页面卡顿。 - 兼容性:第三方库需检查对目标浏览器的支持情况。
- 无障碍:滑动组件应提供键盘导航支持(如箭头键控制)。






