SoFunction
Updated on 2025-04-05

Implementing div drag and drop function in Vue3

1. Create a div

<template>
  <div class="draggable" :style="{ left: `${x}px`, top: `${y}px` }" @mousedown="startDrag">
    Drag me
  </div>
</template>

Code

<script setup>
import { ref } from 'vue';
// Used to store responsive references to the X and Y positions of elementsconst x = ref(500);
const y = ref(500);
// Sign of whether to dragconst isDragging = ref(false);
// Function to start draggingconst startDrag = (event) => {
  // Record the initial mouse position  const initialMouseX = ;
  const initialMouseY = ;
  // Record the initial element position  const initialX = ;
  const initialY = ;
  // Start dragging, set to true   = true;
  // Function executed when the mouse moves  const dragging = (moveEvent) => {
    // Only executed when dragging    if () {
      // Calculate the distance the mouse moves      const deltaX =  - initialMouseX;
      const deltaY =  - initialMouseY;
      // Update the location of the element       = initialX + deltaX;
       = initialY + deltaY;
    }
  };
  // Function that stops dragging when the mouse is released  const stopDrag = () => {
    // End drag, set to false     = false;
    // Remove event listener    ('mousemove', dragging);
    ('mouseup', stopDrag);
  };
  // Add event listener when mouse moves and releases  ('mousemove', dragging);
  ('mouseup', stopDrag);
};
</script>

style

<style>
.draggable {
  width: 550px;
  height: 550px;
  border: 1px solid #000;
  position: fixed;
  cursor: grab; /* Set the mouse style to crawlable state */
  z-index: 100;
}
</style>

This is the end of this article about implementing the div drag function in Vue3. For more related Vue3 div drag content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!