ant-design-vue@next的弹窗组件如何实现拖拽移动?

本案例的代码采取非侵入式的全局事件监听方式。

步骤1:编写dialogdrag.ts

/*弹窗拖拽,适用于ant design */

let draging = false;
let dragDom: HTMLElement | null;
let dragpoint: { x: number, y: number };

document.addEventListener('mousedown', (ev: MouseEvent) => {
    let target = ev.target as HTMLElement;
    //点住标题栏进行拖拽
    if (!target.classList.contains('ant-modal-title')) {
        return;
    }
    //根据标题栏的dom找到控制弹窗组件布局位置的dom,ant-design的弹窗组件的外壳在标题栏的父级第3层
    dragDom = target.parentElement?.parentElement?.parentElement as HTMLElement;
    //由于此拖拽法对所有弹窗有效,通过classname标注控制动作取消
    if (dragDom.parentElement?.classList.contains('nodrag')) {
        dragDom = null;
        return;
    }
    draging = true;
    dragpoint = {
        x: ev.clientX,
        y: ev.clientY
    }
});
document.addEventListener('mouseup', () => {
    draging = false;
    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
        }
    }
});

步骤2:在main.ts中引入步骤1的代码

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios';
import '@/@utils/dialogdrag';
const app = createApp(App);
app.use(store).use(router).mount('#app');
axios.defaults.baseURL = 'api/';

好了,项目中的所有Modal组件都可以按住标题栏进行拖拽移动了。
如果部分弹窗不想拖拽移动怎么办?

给Modal组件的wrapClassName属性设nodrag

 

你可能感兴趣的:(web前端,vue,typescript)