vue实现滑动div
Vue 实现滑动 Div 的方法
使用 CSS 过渡和 Vue 事件
通过 Vue 的 @touchstart、@touchmove 和 @touchend 事件结合 CSS 过渡效果实现滑动效果。需要计算触摸起始位置和移动距离,动态更新 Div 的位置。
<template>
<div
class="slider"
@touchstart="startDrag"
@touchmove="onDrag"
@touchend="endDrag"
:style="{ transform: `translateX(${currentX}px)` }"
>
可滑动内容
</div>
</template>
<script>
export default {
data() {
return {
startX: 0,
currentX: 0,
isDragging: false
};
},
methods: {
startDrag(e) {
this.startX = e.touches[0].clientX - this.currentX;
this.isDragging = true;
},
onDrag(e) {
if (this.isDragging) {
this.currentX = e.touches[0].clientX - this.startX;
}
},
endDrag() {
this.isDragging = false;
}
}
};
</script>
<style>
.slider {
transition: transform 0.3s ease;
touch-action: none;
}
</style>
使用第三方库(如 vue-draggable)
vue-draggable 是一个基于 Sortable.js 的 Vue 拖拽库,可以快速实现滑动和拖拽功能。安装后直接使用组件即可。
安装:
npm install vuedraggable
示例代码:
<template>
<draggable v-model="items" @start="drag=true" @end="drag=false">
<div v-for="item in items" :key="item.id">
{{ item.name }}
</div>
</draggable>
</template>
<script>
import draggable from 'vuedraggable';
export default {
components: { draggable },
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
]
};
}
};
</script>
使用 CSS Scroll Snap
如果需求是横向滑动浏览内容,可以使用 CSS 的 scroll-snap 特性实现流畅的滑动效果。这种方法不需要 JavaScript,纯 CSS 实现。
<template>
<div class="slider-container">
<div class="slider">
<div class="slide">Slide 1</div>
<div class="slide">Slide 2</div>
<div class="slide">Slide 3</div>
</div>
</div>
</template>
<style>
.slider-container {
overflow-x: auto;
scroll-snap-type: x mandatory;
}
.slider {
display: flex;
width: max-content;
}
.slide {
scroll-snap-align: start;
width: 100vw;
flex-shrink: 0;
}
</style>
使用 Swiper.js
Swiper.js 是一个强大的滑动库,支持 Vue 封装。适用于复杂的滑动需求,如轮播、缩略图导航等。
安装:
npm install swiper vue-awesome-swiper
示例代码:

<template>
<swiper :options="swiperOptions">
<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 },
data() {
return {
swiperOptions: {
slidesPerView: 1,
spaceBetween: 30
}
};
}
};
</script>
以上方法可以根据具体需求选择,从简单的 CSS 过渡到复杂的第三方库均可实现滑动效果。






