Vue3 + Ant Design Vue Modal 对话框可拖拽指令
在Vue 3和Ant Design Vue中创建一个可拖拽的对话框,你可以使用自定义指令来实现拖拽功能。以下是一个简单的实现示例:
- 创建一个拖拽指令
v-draggable.modal
:
// draggable.js
import { ref, onMounted, onBeforeUnmount } from 'vue';
export const draggable = {
mounted(el, binding) {
const dragging = ref(false);
let X, Y, x, y, iX, iY;
const dragStart = (e) => {
dragging.value = true;
X = e.clientX - el.offsetLeft;
Y = e.clientY - el.offsetTop;
iX = e.clientX;
iY = e.clientY;
document.onmousemove = dragMove;
document.onmouseup = dragEnd;
};
const dragMove = (e) => {
if (dragging.value) {
x = e.clientX - X;
y = e.clientY - Y;
el.style.left = x + 'px';
el.style.top = y + 'px';
}
};
const dragEnd = () => {
dragging.value = false;
document.onmousemove = null;
document.onmouseup = null;
};
el.addEventListener('mousedown', dragStart);
onBeforeUnmount(() => {
el.removeEventListener('mousedown', dragStart);
});
}
};
- 在你的组件中使用这个指令:
<template>
<a-modal
v-draggable.modal
title="可拖拽的对话框"
:visible="visible"
@ok="handleOk"
@cancel="handleCancel"
>
<p>这是一个可以拖拽的对话框</p>
</a-modal>
</template>
<script setup>
import { ref } from 'vue';
import { Modal } from 'ant-design-vue';
import { draggable } from './draggable.js'; // 引入刚才创建的draggable.js文件
const visible = ref(true);
const handleOk = () => {
visible.value = false;
};
const handleCancel = () => {
visible.value = false;
};
</script>
<style>
/* 确保拖拽时modal不会超出屏幕 */
.ant-modal-content {
cursor: move;
position: absolute;
}
</style>
在这个例子中,我们创建了一个自定义指令v-draggable.modal
,它会给Ant Design Vue的Modal组件添加拖拽功能。你可以将这个指令应用于任何你想要能够拖拽的元素。记得在你的组件中引入指令并使用它。
评论已关闭