vue实现滑动元素
Vue 实现滑动元素的几种方法
使用 CSS Transitions 和 Vue 绑定
通过 Vue 的 v-bind 动态绑定样式,结合 CSS 的 transition 属性实现平滑滑动效果。
<template>
<div class="slider-container">
<div
class="slider"
:style="{ transform: `translateX(${position}px)` }"
@mousedown="startDrag"
@touchstart="startDrag"
></div>
</div>
</template>
<script>
export default {
data() {
return {
position: 0,
isDragging: false,
startX: 0
}
},
methods: {
startDrag(e) {
this.isDragging = true
this.startX = e.type === 'mousedown' ? e.clientX : e.touches[0].clientX
document.addEventListener('mousemove', this.onDrag)
document.addEventListener('touchmove', this.onDrag)
document.addEventListener('mouseup', this.endDrag)
document.addEventListener('touchend', this.endDrag)
},
onDrag(e) {
if (!this.isDragging) return
const clientX = e.type === 'mousemove' ? e.clientX : e.touches[0].clientX
this.position = clientX - this.startX
},
endDrag() {
this.isDragging = false
document.removeEventListener('mousemove', this.onDrag)
document.removeEventListener('touchmove', this.onDrag)
}
}
}
</script>
<style>
.slider-container {
width: 100%;
height: 50px;
position: relative;
}
.slider {
width: 50px;
height: 50px;
background-color: #42b983;
transition: transform 0.2s ease;
cursor: grab;
}
</style>
使用第三方库(如 vue-draggable)
对于更复杂的拖拽需求,可以使用专门的 Vue 拖拽库如 vue-draggable。
安装:
npm install vuedraggable
使用示例:
<template>
<draggable
v-model="list"
@start="drag=true"
@end="drag=false"
>
<div v-for="element in list" :key="element.id">
{{ element.name }}
</div>
</draggable>
</template>
<script>
import draggable from 'vuedraggable'
export default {
components: { draggable },
data() {
return {
list: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
]
}
}
}
</script>
实现横向滑动列表
对于移动端常见的横向滑动列表,可以使用 CSS 的 overflow-x 和 scroll-snap 特性。
<template>
<div class="horizontal-scroll">
<div
v-for="item in items"
:key="item.id"
class="scroll-item"
>
{{ item.content }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, content: 'Slide 1' },
{ id: 2, content: 'Slide 2' }
]
}
}
}
</script>
<style>
.horizontal-scroll {
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
-webkit-overflow-scrolling: touch;
}
.scroll-item {
flex: 0 0 auto;
width: 80vw;
height: 200px;
scroll-snap-align: start;
margin-right: 10px;
background: #eee;
}
</style>
注意事项
- 移动端触摸事件需要添加
touch-actionCSS 属性防止浏览器默认行为 - 性能优化:对于大量可滑动元素,考虑使用虚拟滚动
- 无障碍访问:为可滑动元素添加适当的 ARIA 属性
以上方法可以根据具体需求选择使用,CSS 方案适合简单交互,而第三方库则提供更完整的拖拽功能。







