vue3中实现弹出框进行拖拽时拖拽鼠标在弹出框外面
时间: 2024-01-09 18:45:23 浏览: 64
在Vue3中实现弹出框进行拖拽时拖拽鼠标在弹出框外面,需要将拖拽事件绑定到整个页面上,而不是绑定到弹出框上。具体实现可以参考以下代码:
1. 在弹出框的父级元素上绑定mousedown和mousemove事件,用于计算拖拽距离。
```html
<template>
<div class="modal-container" @mousedown="handleMouseDown">
<div class="modal" :style="{left: left + 'px', top: top + 'px'}">
<slot></slot>
</div>
</div>
</template>
<script>
export default {
data() {
return {
left: 0,
top: 0,
startX: 0,
startY: 0
}
},
methods: {
handleMouseDown(e) {
this.startX = e.pageX
this.startY = e.pageY
document.addEventListener('mousemove', this.handleMouseMove)
document.addEventListener('mouseup', this.handleMouseUp)
},
handleMouseMove(e) {
const distanceX = e.pageX - this.startX
const distanceY = e.pageY - this.startY
this.left += distanceX
this.top += distanceY
this.startX = e.pageX
this.startY = e.pageY
},
handleMouseUp() {
document.removeEventListener('mousemove', this.handleMouseMove)
document.removeEventListener('mouseup', this.handleMouseUp)
}
}
}
</script>
```
2. 在整个页面上绑定mouseup事件,用于解绑mousemove事件。
```html
<template>
<div class="modal-container" @mousedown="handleMouseDown">
<div class="modal" :style="{left: left + 'px', top: top + 'px'}">
<slot></slot>
</div>
</div>
</template>
<script>
export default {
data() {
return {
left: 0,
top: 0,
startX: 0,
startY: 0
}
},
mounted() {
document.addEventListener('mouseup', this.handleMouseUp)
},
beforeUnmount() {
document.removeEventListener('mouseup', this.handleMouseUp)
},
methods: {
handleMouseDown(e) {
this.startX = e.pageX
this.startY = e.pageY
document.addEventListener('mousemove', this.handleMouseMove)
},
handleMouseMove(e) {
const distanceX = e.pageX - this.startX
const distanceY = e.pageY - this.startY
this.left += distanceX
this.top += distanceY
this.startX = e.pageX
this.startY = e.pageY
},
handleMouseUp() {
document.removeEventListener('mousemove', this.handleMouseMove)
}
}
}
</script>
```
这样就可以实现拖拽弹出框时,鼠标在弹出框外面也能拖拽了。
阅读全文