当前位置:首页 > 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 HTML5 提供了原生的拖拽 API,可以通过 draggable 属性、dragstart、dragend、dragover 和 dr…

vue 实现拖拽布局

vue 实现拖拽布局

Vue 实现拖拽布局的方法 使用原生HTML5拖拽API 通过HTML5的draggable属性和Vue的事件绑定实现基础拖拽功能。在元素上添加draggable="true",并通过@dragsta…

vue实现拖拽组件

vue实现拖拽组件

Vue 实现拖拽组件的方法 使用 HTML5 原生拖拽 API HTML5 提供了原生的拖拽 API,可以通过 draggable 属性、dragstart、dragend、dragover 和 dr…

Vue拖拽怎么实现

Vue拖拽怎么实现

Vue拖拽实现方法 使用Vue实现拖拽功能可以通过原生HTML5的拖拽API或第三方库如vuedraggable来实现。以下是两种常见的方法: 使用HTML5拖拽API HTML5提供了原生的拖拽A…

vue实现可拖拽

vue实现可拖拽

实现拖拽功能的基本方法 在Vue中实现拖拽功能通常可以通过HTML5的Drag and Drop API或第三方库如vuedraggable来完成。以下是两种主要实现方式: 使用HTML5原生API…

vue实现拖拽分类

vue实现拖拽分类

Vue 实现拖拽分类的方法 使用原生 HTML5 拖放 API HTML5 提供了原生的拖放 API,可以通过 draggable 属性、dragstart、dragend、dragover 和 dr…