当前位置:首页 > VUE

Vue实现鼠标拖拽滚动

2026-02-22 11:20:27VUE

实现鼠标拖拽滚动的基本思路

在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>

脚本部分处理拖拽逻辑:

Vue实现鼠标拖拽滚动

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;
}

垂直滚动支持

若需支持垂直方向拖拽,修改方法如下:

Vue实现鼠标拖拽滚动

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
  // 其余逻辑相同
}

标签: 鼠标拖拽
分享给朋友:

相关文章

vue拖拽容器实现

vue拖拽容器实现

实现 Vue 拖拽容器的基本方法 使用 HTML5 原生拖拽 API 通过 draggable 属性和拖拽事件(dragstart、dragend、dragover、drop)实现基础拖拽功能。适用于…

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽功能。以下是核心代码逻辑: const draggableElement = document.…

vue实现carousel拖拽

vue实现carousel拖拽

实现拖拽轮播的基本思路 在Vue中实现可拖拽的Carousel组件需要结合触摸事件(touchstart、touchmove、touchend)和鼠标事件(mousedown、mousemove、mo…

vue实现盒子拖拽

vue实现盒子拖拽

实现盒子拖拽的基本思路 在Vue中实现盒子拖拽功能,可以通过监听鼠标事件(mousedown、mousemove、mouseup)来实现。核心逻辑是记录拖拽起始位置,计算位移差值,并更新盒子的位置。…

vue实现图表拖拽

vue实现图表拖拽

Vue 实现图表拖拽功能 在 Vue 中实现图表拖拽功能,可以通过结合第三方图表库(如 ECharts、Chart.js)和拖拽库(如 interact.js、draggable)来完成。以下是几种常…

vue实现拖拽上传

vue实现拖拽上传

Vue 拖拽上传实现方法 使用 HTML5 原生拖拽 API 在 Vue 中可以通过监听原生拖拽事件实现基础功能: <template> <div class="dr…