vue 使用自定义指令实现元素拖拽

1.在项目src目录下可以新建一个文件夹 ,取名为 directive ,在该目录中创建drag.js , 代码如下:

/**
 * @file 自定义拖拽命令
 */

import Vue from 'vue';
 
export default   {
            bind(el: any) {
                el.style.position = 'absolute';
                el.style.zIndex = el.style.zIndex || '3000';
            },

            inserted(el: any) {
                // 设置元素初始位置
                const boundingClientRect = el.getBoundingClientRect();
                el.style.left = boundingClientRect.x + 'px';
                el.style.top = boundingClientRect.y + 'px';
                // 将拖拽元素置于body子元素,防止被relative的父元素遮挡
                document.body.appendChild(el);

                let originX: number;
                let originY: number;
                const mouseDownHandler = (evt: MouseEvent) => {
                    originX = evt.clientX - el.offsetLeft;
                    originY = evt.clientY - el.offsetTop;
                    el.style.cursor = 'pointer';
                };
                const mouseMoveHandler = (evt: MouseEvent) => {
                    if (evt.buttons === 1 && originX && originY) {
                        el.style.left = evt.clientX - originX + 'px';
                        el.style.top = evt.clientY - originY + 'px';
                    }
                };
                const mouseUpHandler = () => {
                    el.style.cursor = 'default';
                };
                el.addEventListener('mousedown', mouseDownHandler);
                el.addEventListener('mousemove', mouseMoveHandler);
                el.addEventListener('mouseup', mouseUpHandler);
                el.__mouseDownHandler__ = mouseDownHandler;
                el.__mouseMoveHandler__ = mouseMoveHandler;
                el.__mouseUpHandler__ = mouseUpHandler;
            },

            unbind(el: any) {
                el.removeEventListener('mousedown', el.__mouseDownHandler__);
                el.removeEventListener('mousemove', el.__mouseMoveHandler__);
                el.removeEventListener('mouseup', el.__mouseUpHandler__);
                // 当父组件销毁触发unbind的时候需要手动删除这个节点,不然会一直存留在body中
                el.parentNode.removeChild(el);
            }
}

2.在当前文件夹里新建index.js

import drag from "./drag .js";

var xhDirective = {
    drag :drag ,
}

const install = function(Vue) {
    Object.keys(xhDirective).forEach(key => {
        Vue.directive(key, xhDirective[key]);
    });
    
};

const API = {
    install,
    ...xhDirective
};

export default API;

3.在项目的主文件mian.js中引入,使用vue.use()来注册系统 的公共指令(部分代码)

import Vue from 'vue';
import directive from "./directive"
Vue.use(directive)

注:拖拽效果实现代码原文链接:https://blog.csdn.net/csu_passer/article/details/105709661

你可能感兴趣的:(vue 使用自定义指令实现元素拖拽)