vue自定义指令让el-dialog可以自由拖动

先看看效果

el-dialog自由拖动

使用方式,只需要添加自定义指令 v-drag2anywhere

<el-dialog v-drag2anywhere

           title="弹窗标题"
           :visible.sync="visible"
           append-to-body>
</el-dialog>

编写自定义指令,我把它写成一个directive.js

// Vue自定义指令

// dialog可以拖来拖去
const directive = Vue => {
    Vue.directive('drag2anywhere', {
    // 当被绑定的元素插入到 DOM 中时……
        inserted: (el) => {
            el.style.overflow = 'hidden';
            const target = el.childNodes[0];
            const targetHeader = target.childNodes[0];
            let isOnclick = false;
            let mouseX;
            let mouseY;
            let objX;
            let objY;
            targetHeader.onmousedown = (event) => {
                isOnclick = true;
                target.style.cursor = 'move';
                target.style.left = target.offsetLeft + 'px'; // 先记录之前的位置
                target.style.top = target.offsetTop + 'px'; // 先记录之前的位置
                target.style.margin = '0'; // 去掉margin
                mouseX = event.clientX;
                mouseY = event.clientY;
                objX = parseInt(target.style.left || target.offsetLeft);
                objY = parseInt(target.style.top || target.offsetTop);
                document.onmousemove = null; // 解绑监听鼠标拖动事件
                document.onmousemove = (event) => { // 监听鼠标拖动事件
                    if (isOnclick) {
                        event = event || window.event;
                        target.style.left = parseInt(event.clientX - mouseX + objX) + 'px';
                        target.style.top = parseInt(event.clientY - mouseY + objY) + 'px';
                    }
                };
            };
            targetHeader.onmouseup = (event) => { // 松开鼠标
                isOnclick = false;
                target.style.cursor = 'default';
            };
        }
    });
};
export default directive;

最后在main.js里引用自定义指令:

// 引入自定义指令
import directive from './public/utils/directive';
// 注册自定义指令
Vue.use(directive);
自定义指令使用方式

收工!

类似文章

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注