1.创建一个div
<template>
<div class="draggable" :style="{ left: `${x}px`, top: `${y}px` }" @mousedown="startDrag">
拖拽我
</div>
</template>
2.typescript代码
<script setup>
import { ref } from 'vue';
const x = ref(500);
const y = ref(500);
const isDragging = ref(false);
const startDrag = (event) => {
const initialMouseX = event.clientX;
const initialMouseY = event.clientY;
const initialX = x.value;
const initialY = y.value;
isDragging.value = true;
const dragging = (moveEvent) => {
if (isDragging.value) {
const deltaX = moveEvent.clientX - initialMouseX;
const deltaY = moveEvent.clientY - initialMouseY;
x.value = initialX + deltaX;
y.value = initialY + deltaY;
}
};
const stopDrag = () => {
isDragging.value = false;
document.removeEventListener('mousemove', dragging);
document.removeEventListener('mouseup', stopDrag);
};
document.addEventListener('mousemove', dragging);
document.addEventListener('mouseup', stopDrag);
};
</script>
3.CSS样式
<style>
.draggable {
width: 550px;
height: 550px;
border: 1px solid #000;
position: fixed;
cursor: grab;
z-index: 100;
}
</style>