写一个vue自定义指令,element dialog顶部拖拽,并且不能拖离页面
时间: 2023-08-25 20:36:19 浏览: 168
好的,下面是一个实现element dialog顶部拖拽的Vue自定义指令,并且限制其不能拖离页面的示例代码:
```javascript
// draggable.js
export default {
inserted(el, binding) {
const dialogHeaderEl = el.querySelector('.el-dialog__header')
const dialogWrapperEl = el.querySelector('.el-dialog__wrapper')
const containmentEl = binding.value ? document.querySelector(binding.value) : dialogWrapperEl
let isDragging = false
let lastX = 0
let lastY = 0
dialogHeaderEl.style.cursor = 'move'
dialogHeaderEl.addEventListener('mousedown', (e) => {
isDragging = true
lastX = e.clientX
lastY = e.clientY
document.addEventListener('mousemove', handleMouseMove)
document.addEventListener('mouseup', handleMouseUp)
})
function handleMouseMove(e) {
if (isDragging) {
const deltaX = e.clientX - lastX
const deltaY = e.clientY - lastY
const dialogRect = dialogWrapperEl.getBoundingClientRect()
const containmentRect = containmentEl.getBoundingClientRect()
let newLeft = dialogRect.left + deltaX
let newTop = dialogRect.top + deltaY
// Limit the dialog to the containment element
if (newLeft < containmentRect.left) {
newLeft = containmentRect.left
}
if (newTop < containmentRect.top) {
newTop = containmentRect.top
}
if (newLeft + dialogRect.width > containmentRect.right) {
newLeft = containmentRect.right - dialogRect.width
}
if (newTop + dialogRect.height > containmentRect.bottom) {
newTop = containmentRect.bottom - dialogRect.height
}
dialogWrapperEl.style.left = newLeft + 'px'
dialogWrapperEl.style.top = newTop + 'px'
lastX = e.clientX
lastY = e.clientY
}
}
function handleMouseUp() {
isDragging = false
document.removeEventListener('mousemove', handleMouseMove)
document.removeEventListener('mouseup', handleMouseUp)
}
}
}
```
上述代码定义了一个名为`draggable`的Vue自定义指令,可以用于实现element dialog顶部拖拽的效果,并且限制其不能拖离页面。该指令监听了dialog header元素的mousedown、mousemove和mouseup事件,并且根据鼠标的移动距离来实现拖拽效果。同时,通过传入`value`参数来指定限制拖拽区域的父级元素选择器。
使用该自定义指令的示例如下:
```vue
<template>
<el-dialog v-draggable=".container">
<div class="el-dialog__header">
<span>{{ title }}</span>
</div>
<div class="el-dialog__body">
{{ content }}
</div>
</el-dialog>
</template>
<script>
import draggable from '@/directives/draggable'
export default {
directives: {
draggable
},
data() {
return {
title: 'Dialog Title',
content: 'Dialog Content'
}
}
}
</script>
```
在上述代码中,我们为el-dialog元素添加了`v-draggable=".container"`指令,表示限制拖拽区域的父级元素选择器为`.container`。注意,我们需要为dialog header元素添加一个类名为`el-dialog__header`的div,以便在指令中获取到该元素进行拖拽。
阅读全文