实现原理:
利用vue创造一个自定义指令,绑定到需要拖拽移动的el-dialog组件上,在自定义指令中处理弹窗拖拽。

步骤1:创建自定义指令

// v-dialogDrag: 弹窗拖拽
import Vue from 'vue';
let draging = false;
let dragDom: HTMLElement | null;
let dragpoint: { x: number, y: number };
Vue.directive('dialogDrag', {
    bind(el, binding, vnode, oldVnode) {
        let dialogHeaderEl = el.querySelector('.el-dialog__header') as HTMLElement;
        dialogHeaderEl.addEventListener('mousedown', (ev: MouseEvent) => {
        	let target = ev.target as HTMLElement;
        	//由于点击关闭按钮会事件冒泡,取消拖拽
            if (target.classList.contains('el-dialog__close')) {
                return;
            }
            draging = true;
            dragDom = el.querySelector('.el-dialog');
            //自定义样式,让弹窗在拖拽过程中鼠标指针变成十字移动
            dragDom?.classList.add('draging');
            dragpoint = {
                x: ev.clientX,
                y: ev.clientY
            }
        });
    }
});
document.addEventListener('mouseup', (ev: MouseEvent) => {
    draging = false;
    dragDom?.classList.remove('draging');
    dragDom = null;
});
document.addEventListener('mousemove', (ev: MouseEvent) => {
    if (draging) {
        let _dragdom = dragDom as HTMLElement;
        let sty = window.getComputedStyle(_dragdom, null);
        _dragdom.style.marginLeft = `${parseFloat(sty.marginLeft) + ev.clientX - dragpoint.x}px`;
        _dragdom.style.marginTop = `${parseFloat(sty.marginTop) + ev.clientY - dragpoint.y}px`;
        dragpoint = {
            x: ev.clientX,
            y: ev.clientY
        }
    }
});

将上述内容保存到一个ts文件中,命名随意,比如dialogdrag.ts
为了便于管理,咱把它放到@utils目录下,这个随意。

步骤2:在vue项目的main.ts中引入步骤1的文件。

import '@/@utils/dialogdrag.ts';

步骤3:给el-dialog组件加上自定义指令

<el-dialog v-dialogDrag></el-dialog>

好了,这个弹窗就能拖拽移动了

Logo

前往低代码交流专区

更多推荐