Skip to content

实现原生拖拽

vue
<template>
  <div style="border: 1px solid red;width: 100vw;height: 100vh;">
    <!-- 设置 draggable 属性,支持元素拖动 -->
    <div draggable="true" style="padding: 10px; border: 1px solid #ccc;position: absolute;"
      :style="{ top: top + 'px', left: left + 'px' }" @dragstart="dragstart" @dragend="dragend">
      拖动我
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const top = ref(0);
const left = ref(0);
const x = ref(0);
const y = ref(0);

function dragstart(e) {
  // 拿到 开始拖动的 x、y 值
  console.log(e, 'e', 'dragstart');
  x.value = e.x;
  y.value = e.y;
}

function dragend(e) {
  // 拿到 拖动结束的 x、y 值
  // 计算 x 和 y 的相对变化
  // left 加上 x 的相对变化值
  // top 加上 y 的相对变化值  
  console.log(e, 'e', 'dragend');
  left.value += e.x - x.value;
  top.value += e.y - y.value;
}
</script>