In the blog “Vue advanced (ninety-one) : Custom instruction” explained the creation method of Vue custom instruction (local, global), and the related hook function of the instruction. This blog on this basis to achieve vUE custom drag instructions.

1. Define global drag directives:

Directive (‘drag’,{}) in main.js; Can. Instead, create a new drag.js file for your project, implement drag logic inside the js file, and call this directive in dom code:

(1) Create a drag. Js file:

import Vue from 'vue'; Use vue.directive () to define a global directive //1. Parameter 1: the name of the instruction, which is not preceded by v- //2. Parameter 2: is an object with the associated operation function //3. Directive ('drag',{//1) {//1 The bind function is executed immediately after the instruction is bound to an element, only once //2. The first argument in each function is always el, representing the element of the binding instruction, and el is the native JS object //3. There is no way to get focus through el.focus(), because this takes effect only after the DOM is inserted bind:function(el){}, // INSERTED denotes an element, and the inserted into the DOM will execute the inserted function, Inserted :function(el){el.onmousedown = function(e){var disx = e.pagex - el.offsetLeft; var disy = e.pageY - el.offsetTop; document.onmousemove = function (e) { el.style.left = e.pageX - disx + 'px'; el.style.top = e.pageY - disy + 'px'; } document.onmouseup = function () { document.onmousemove = document.onmouseup = null; }}}, // Function (el) {}}) export default drag;Copy the code

(2) Import this file in main.js. Don’t need a vue. Use ();

Import drag from './directive/drag'Copy the code

(3) Call directly in the page

<div v-if="show" v-drag></div>
Copy the code

2. Define local drag instructions:

Local instructions only need to be in the corresponding.vueOn the page, adddirectivesAttribute, and indirectivesTo write the corresponding instruction.