写一个vue3的拖拽div
时间: 2023-11-14 22:09:29 浏览: 105
好的,以下是一个简单的 Vue3 拖拽组件实现,你可以在需要拖拽的元素上绑定 v-draggable 指令来使用:
```html
<template>
<div class="drag-wrapper">
<div v-draggable class="drag-element" :style="{ left: x + 'px', top: y + 'px' }">
拖拽我~
</div>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
directives: {
draggable: {
mounted(el) {
let isDragging = false
let currentX = 0
let currentY = 0
let initialX = 0
let initialY = 0
let xOffset = 0
let yOffset = 0
el.addEventListener('mousedown', dragStart)
el.addEventListener('mouseup', dragEnd)
el.addEventListener('mousemove', drag)
function dragStart(e) {
initialX = e.clientX - xOffset
initialY = e.clientY - yOffset
if (e.target === el) {
isDragging = true
}
}
function dragEnd(e) {
initialX = currentX
initialY = currentY
isDragging = false
}
function drag(e) {
if (isDragging) {
e.preventDefault()
currentX = e.clientX - initialX
currentY = e.clientY - initialY
xOffset = currentX
yOffset = currentY
el.style.left = currentX + 'px'
el.style.top = currentY + 'px'
}
}
}
}
},
setup() {
const x = ref(0)
const y = ref(0)
return {
x,
y
}
}
}
</script>
```
希望能对你有所帮助!
阅读全文