当前位置:首页 > VUE

vue实现拖动div

2026-01-19 01:44:03VUE

实现拖动 div 的基本思路

在 Vue 中实现拖动 div 的功能,可以通过监听鼠标事件(mousedownmousemovemouseup)来动态更新元素的位置。核心逻辑是记录初始点击位置,计算移动偏移量,并更新元素的 transformleft/top 样式。

使用原生事件实现拖动

创建一个可拖动的 div,通过 Vue 的指令或方法绑定事件。

vue实现拖动div

<template>
  <div
    ref="draggable"
    class="draggable"
    @mousedown="startDrag"
    :style="{ transform: `translate(${position.x}px, ${position.y}px)` }"
  >
    拖动我
  </div>
</template>

<script>
export default {
  data() {
    return {
      position: { x: 0, y: 0 },
      isDragging: false,
      startPos: { x: 0, y: 0 },
    };
  },
  methods: {
    startDrag(e) {
      this.isDragging = true;
      this.startPos = {
        x: e.clientX - this.position.x,
        y: e.clientY - this.position.y,
      };
      document.addEventListener('mousemove', this.drag);
      document.addEventListener('mouseup', this.stopDrag);
    },
    drag(e) {
      if (!this.isDragging) return;
      this.position = {
        x: e.clientX - this.startPos.x,
        y: e.clientY - this.startPos.y,
      };
    },
    stopDrag() {
      this.isDragging = false;
      document.removeEventListener('mousemove', this.drag);
      document.removeEventListener('mouseup', this.stopDrag);
    },
  },
};
</script>

<style>
.draggable {
  width: 100px;
  height: 100px;
  background: #42b983;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: move;
  position: absolute;
}
</style>

使用第三方库实现拖动

如果需要更复杂的功能(如边界限制、拖拽手柄),可以使用第三方库如 vuedraggabledraggable-vue-directive

安装 vuedraggable

npm install vuedraggable

示例代码

<template>
  <draggable v-model="list" @start="dragStart" @end="dragEnd">
    <div v-for="item in list" :key="item.id" class="draggable-item">
      {{ item.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' },
      ],
    };
  },
  methods: {
    dragStart() {
      console.log('拖动开始');
    },
    dragEnd() {
      console.log('拖动结束');
    },
  },
};
</script>

<style>
.draggable-item {
  padding: 10px;
  margin: 5px;
  background: #f0f0f0;
  cursor: move;
}
</style>

边界限制与优化

如果需要限制拖动范围,可以在 drag 方法中添加边界判断逻辑。

vue实现拖动div

drag(e) {
  if (!this.isDragging) return;
  const maxX = window.innerWidth - this.$refs.draggable.offsetWidth;
  const maxY = window.innerHeight - this.$refs.draggable.offsetHeight;
  this.position = {
    x: Math.min(maxX, Math.max(0, e.clientX - this.startPos.x)),
    y: Math.min(maxY, Math.max(0, e.clientY - this.startPos.y)),
  };
}

触摸事件支持

为了支持移动端触摸事件,可以添加 touchstarttouchmovetouchend 事件。

startDrag(e) {
  const clientX = e.clientX ?? e.touches[0].clientX;
  const clientY = e.clientY ?? e.touches[0].clientY;
  this.isDragging = true;
  this.startPos = {
    x: clientX - this.position.x,
    y: clientY - this.position.y,
  };
  document.addEventListener('mousemove', this.drag);
  document.addEventListener('touchmove', this.drag);
  document.addEventListener('mouseup', this.stopDrag);
  document.addEventListener('touchend', this.stopDrag);
}

性能优化

频繁更新 DOM 可能引发性能问题,可以通过以下方式优化:

  • 使用 transform 代替 left/top,避免重排。
  • 节流 mousemove 事件,减少更新频率。
  • 在拖动结束时移除事件监听,避免内存泄漏。

标签: 拖动vue
分享给朋友:

相关文章

vue实现mui

vue实现mui

使用 Vue 实现 MUI(Material-UI)风格的界面 Vue 本身不直接提供 MUI(Material Design)组件,但可以通过集成第三方库或手动实现来达到类似效果。以下是几种常见方法…

vue jwt实现

vue jwt实现

Vue JWT 实现方法 安装依赖 确保项目中安装了 jsonwebtoken(后端)和 axios(前端)。若使用 Vue 3,可搭配 vue-router 和 pinia(或 vuex)管理状态。…

vue指令实现

vue指令实现

Vue 指令的实现方式 Vue 指令是特殊的标记,用于在 DOM 元素上应用特定的行为。可以通过全局或局部方式注册自定义指令。 全局注册指令 在 Vue 应用中通过 Vue.directive 方法…

vue实现tip

vue实现tip

Vue实现Tooltip的方法 使用Vue实现Tooltip可以通过多种方式完成,以下是几种常见的方法: 使用原生HTML的title属性 在Vue模板中直接使用HTML的title属性是最简单的实…

vue实现首页

vue实现首页

Vue 实现首页的基本步骤 安装 Vue.js 和相关依赖,可以通过 Vue CLI 或 Vite 快速初始化项目。Vue CLI 适合传统项目,Vite 更适合现代前端开发。 npm instal…

不用vue实现spa

不用vue实现spa

使用原生 JavaScript 实现 SPA 通过监听 URL 变化动态加载内容,结合 history.pushState 或 hashchange 事件实现路由切换。 // 路由配置 const…