antd-vue的modal组件不能拖拽移动位置,于是我通过vue的自定义组件实现了拖拽
// main.js
// main.js
const app = createApp(App);
// 定义指令,实现modal拖拽
app.directive('drag-modal', {
mounted(header) {
// 使用的时候把指令放在了自定义header上,所以需要通过parentNode获取到modal节点
const modal = header.parentNode.parentNode.parentNode;
const headerOffset = header.offsetLeft;
header.onmousedown = (e) => {
let startX = e.offsetX,
startY = e.offsetY;
const moveModal = (e) => {
let offsetTop = e.clientY - startY;
let offsetLeft = e.clientX - startX - headerOffset;
// 避免移动到窗口外面去
if (offsetTop > modal.parentNode.clientHeight - modal.clientHeight) {
offsetTop = modal.parentNode.clientHeight - modal.clientHeight;
}
if (offsetLeft > modal.parentNode.clientWidth - modal.clientWidth) {
offsetLeft = modal.parentNode.clientWidth - modal.clientWidth;
}
if (offsetTop < 0) offsetTop = 0;
if (offsetLeft < 0) offsetLeft = 0;
modal.style.left = offsetLeft + 'px'
modal.style.top = offsetTop + 'px'
// console.log(e, offsetLeft, offsetTop);
}
document.body.addEventListener('mousemove', moveModal);
document.body.addEventListener('mouseup', e => {
document.body.removeEventListener('mousemove', moveModal);
})
}
}
});
app.use(Antd).mount('#app');
接下来就可以使用定义好的v-drag-modal指令了:
<a-modal v-model:visible="dialogVisible" wrapClassName="moveable-modal" :width="360" centered
:mask="false" :maskClosable="false" :footer="null" :header="null" size="small">
<a-row class="modal-header" v-drag-modal>
自定义标题
</a-row>
</a-modal>
这里只贴了关键代码,需要补全缺少的变量才能运行。