Vue achieves simple drag and drop effects

  • 2021-08-06 20:52:34
  • OfStack

In this paper, we share the specific code of Vue to realize simple drag and drop effect for your reference. The specific contents are as follows

Custom directives v-drag

l can only be dragged horizontally when it exists

t can only be dragged vertically when it exists

lt can be dragged in any direction when it exists


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title> Drag and drop </title>
 <style>
  *{
   margin: 0;
   padding: 0;
  }
  #box{
   background: red;
   width: 100px;
   height: 100px;
   position: absolute;
 
  }
 </style>
 <script src="vue.js"></script>
</head>
<body>
 <div id="app">
  <div id="box" v-drag.l.t="flag"></div>
 </div>
 <script>
  Vue.directive("drag",(el,{modifiers,value})=>{
   let{l,t}=modifiers;
 
 
   el.addEventListener("mousedown",handleDownCb)
 
   let disX,disY;
   function handleDownCb(e){
    disX=e.offsetX;
    disY=e.offsetY;
    // console.log(disX,disY)
    document.addEventListener("mousemove",handleMoveCb);
    document.addEventListener("mouseup",handleUpCb);
   }
 
   function handleMoveCb(e){
    let x=e.clientX-disX;
    let y=e.clientY-disY;
    if((l&&t) && value){
     el.style.left=x+"px";     
     el.style.top=y+"px";
     return;
    }
 
    if(l&&value){
     el.style.left=x+"px";     
     return;
    }
    if(t&&value){
     el.style.top=y+"px";
     return;
    }
   }
 
   function handleUpCb(){
    document.removeEventListener("mousemove",handleMoveCb);
    document.removeEventListener("mouseup",handleUpCb);
   }
 
  })
  let vm=new Vue({
   el:"#app",
   data:{
    flag:true
   }
  })
 </script>
</body>
</html>

Note:

Change v-drag. l v-drag. t v-drag. l. t to achieve horizontal and vertical drag in any direction


Related articles: