This article describes the use of custom instructions to implement drag and drop behavior. Share it for your reference, as follows:
need
The drag and drop effect is achieved through custom instructions. The expected usage method is:
<div style="background: #f00; width: 200px; height: 200px;" v-drag> XXXX </div>
A more important requirement point:
- Drag the child elements inside the element can prevent the drag behavior by itself
for example:
<div style="background: #f00; width: 200px; height: 200px;" v-drag> <el-button @>test</el-button> </div>
Have used itvue-resizable
, Since this component is implemented through event capture, the drag and drop behavior will also trigger the drag and drop behavior, which does not meet the development needs, the drag and drop instructions are implemented by itself, and the relevant source code is as follows.
No dependencies, copy can be used
Source code
/** * @file Custom drag and drop command */ import Vue from 'vue'; const Drag = { install(Vue: any) { // If you need to prohibit dragging some elements inside the element from triggering drag, add @ to the internal non-triggered drag element. ('drag', { bind(el: any) { = 'absolute'; = || '3000'; }, inserted(el: any) { // Set the initial position of the element const boundingClientRect = (); = + 'px'; = + 'px'; // Place drag element on body child element to prevent being blocked by relative parent element (el); let originX: number; let originY: number; const mouseDownHandler = (evt: MouseEvent) => { originX = - ; originY = - ; = 'pointer'; }; const mouseMoveHandler = (evt: MouseEvent) => { if ( === 1 && originX && originY) { = - originX + 'px'; = - originY + 'px'; } }; const mouseUpHandler = () => { = 'default'; }; ('mousedown', mouseDownHandler); ('mousemove', mouseMoveHandler); ('mouseup', mouseUpHandler); el.__mouseDownHandler__ = mouseDownHandler; el.__mouseMoveHandler__ = mouseMoveHandler; el.__mouseUpHandler__ = mouseUpHandler; }, unbind(el: any) { ('mousedown', el.__mouseDownHandler__); ('mousemove', el.__mouseMoveHandler__); ('mouseup', el.__mouseUpHandler__); // When the parent component is destroyed and triggered unbind, it needs to be deleted manually, otherwise it will remain in the body (el); } }); } }; (Drag); export default Drag;
I hope this article will be helpful to everyone's programming.