Vue3 拖拽元素:实现随鼠标移动
在 Vue3 中,可以通过以下步骤给元素添加一个拖拽事件让其随鼠标移动:
- 在元素上添加一个
mousedown事件,当鼠标按下时触发。 - 在
mousedown事件中添加一个mousemove事件,当鼠标移动时触发。 - 在
mousemove事件中计算元素应该移动的距离,并将其应用到元素的样式上。 - 在
mouseup事件中移除mousemove事件,当鼠标抬起时停止移动。
下面是一个示例代码:
<template>
<div class="drag-container">
<div class="drag-element" @mousedown="startDrag">{{ text }}</div>
</div>
</template>
<script>
export default {
data() {
return {
isDragging: false,
startX: 0,
startY: 0,
currentX: 0,
currentY: 0,
};
},
props: {
text: String,
},
methods: {
startDrag(event) {
this.isDragging = true;
this.startX = event.clientX;
this.startY = event.clientY;
document.addEventListener("mousemove", this.dragElement);
document.addEventListener("mouseup", this.stopDrag);
},
dragElement(event) {
if (this.isDragging) {
this.currentX = event.clientX - this.startX;
this.currentY = event.clientY - this.startY;
const element = event.target;
element.style.transform = `translate(${this.currentX}px, ${this.currentY}px)`;
}
},
stopDrag() {
if (this.isDragging) {
this.isDragging = false;
document.removeEventListener("mousemove", this.dragElement);
document.removeEventListener("mouseup", this.stopDrag);
}
},
},
};
</script>
<style>
.drag-container {
width: 400px;
height: 400px;
background-color: #ddd;
display: flex;
justify-content: center;
align-items: center;
}
.drag-element {
background-color: #fff;
padding: 10px;
border: 1px solid #000;
cursor: move;
}
</style>
在这个示例中,我们在drag-element上添加了一个mousedown事件,并在其中调用了startDrag方法。这个方法设置了isDragging变量为true,并记录了鼠标按下时的坐标。
然后我们在startDrag方法中添加了两个事件监听器:mousemove和mouseup。mousemove事件会调用dragElement方法,在其中计算元素应该移动的距离,并将其应用到元素的样式上。mouseup事件会调用stopDrag方法,在其中移除mousemove和mouseup事件监听器,停止移动。
最后,我们在样式中设置了.drag-element元素的cursor属性为move,让鼠标在元素上时变成拖拽的样式。
原文地址: https://www.cveoy.top/t/topic/noLD 著作权归作者所有。请勿转载和采集!