vue2怎样实现dialog弹框可拖拽
可以通过以下步骤实现Vue2中的dialog弹框可拖拽:
-
在dialog组件中添加一个mousedown事件,以便拖拽时能够获取鼠标的位置。
-
在mousedown事件中添加一个mouseup事件和mousemove事件,以便在鼠标移动时动态改变dialog的位置。
-
在mousemove事件中计算出dialog应该移动的位置,并将其应用到dialog的style属性中。
-
在mouseup事件中移除mousemove事件,以停止拖拽。
下面是一个简单的实现示例:
<template>
<div class="dialog" :style="{ top: top + 'px', left: left + 'px' }">
<div class="title" @mousedown="startDrag">{{ title }}</div>
<div class="content">
<slot></slot>
</div>
</div>
</template>
<script>
export default {
data() {
return {
top: 0,
left: 0,
dragging: false,
startX: 0,
startY: 0
};
},
methods: {
startDrag(e) {
this.dragging = true;
this.startX = e.clientX - this.left;
this.startY = e.clientY - this.top;
document.addEventListener('mouseup', this.stopDrag);
document.addEventListener('mousemove', this.drag);
},
drag(e) {
if (this.dragging) {
this.left = e.clientX - this.startX;
this.top = e.clientY - this.startY;
}
},
stopDrag() {
this.dragging = false;
document.removeEventListener('mouseup', this.stopDrag);
document.removeEventListener('mousemove', this.drag);
}
}
};
</script>
在上面的示例中,我们在dialog组件的title区域添加了一个mousedown事件,用于启动拖拽。在mousedown事件中,我们记录了鼠标的起始位置,并在document上添加了mouseup事件和mousemove事件,用于在拖拽时动态改变dialog的位置。
在mousemove事件中,我们计算出dialog应该移动的距离,并将其应用到dialog的style属性中。在mouseup事件中,我们移除了mousemove事件,以停止拖拽。
需要注意的是,我们在data中添加了dragging、startX和startY三个变量,并在拖拽开始时将dragging设置为true,以便在mousemove事件中判断是否正在拖拽。我们还将startX和startY记录下来,以便在计算dialog应该移动的距离时使用
原文地址: http://www.cveoy.top/t/topic/g1ly 著作权归作者所有。请勿转载和采集!