Vue实现鼠标拖拽滚动
实现鼠标拖拽滚动的基本思路
在Vue中实现鼠标拖拽滚动效果,核心是监听鼠标事件(mousedown、mousemove、mouseup)并计算位移差。通过修改元素的scrollLeft或scrollTop属性实现滚动效果。
基础实现步骤
创建可拖拽滚动的容器组件,模板部分需设置overflow: hidden样式:
<template>
<div
class="scroll-container"
ref="container"
@mousedown="startDrag"
@mousemove="onDrag"
@mouseup="endDrag"
@mouseleave="endDrag"
>
<slot></slot>
</div>
</template>
脚本部分处理拖拽逻辑:

export default {
data() {
return {
isDragging: false,
startX: 0,
scrollLeft: 0
}
},
methods: {
startDrag(e) {
this.isDragging = true
this.startX = e.pageX - this.$refs.container.offsetLeft
this.scrollLeft = this.$refs.container.scrollLeft
},
onDrag(e) {
if (!this.isDragging) return
e.preventDefault()
const x = e.pageX - this.$refs.container.offsetLeft
const walk = (x - this.startX) * 2 // 调整系数控制滚动速度
this.$refs.container.scrollLeft = this.scrollLeft - walk
},
endDrag() {
this.isDragging = false
}
}
}
样式优化
为提升用户体验,建议添加拖拽时的光标样式:
.scroll-container {
overflow-x: auto;
cursor: grab;
user-select: none;
}
.scroll-container:active {
cursor: grabbing;
}
垂直滚动支持
若需支持垂直方向拖拽,修改方法如下:

startDrag(e) {
this.isDragging = true
this.startY = e.pageY - this.$refs.container.offsetTop
this.scrollTop = this.$refs.container.scrollTop
},
onDrag(e) {
if (!this.isDragging) return
const y = e.pageY - this.$refs.container.offsetTop
const walk = y - this.startY
this.$refs.container.scrollTop = this.scrollTop - walk
}
性能优化建议
对于复杂内容,可使用防抖技术减少重绘:
import { debounce } from 'lodash'
methods: {
onDrag: debounce(function(e) {
// 拖拽逻辑
}, 16) // 60fps的帧间隔
}
移动端兼容
添加触摸事件支持以实现移动端适配:
<div
@touchstart="startDrag"
@touchmove="onDrag"
@touchend="endDrag"
></div>
触摸事件处理方法需调整坐标获取方式:
startDrag(e) {
const clientX = e.touches ? e.touches[0].clientX : e.clientX
// 其余逻辑相同
}






