vue ----自定义指令,实现拖拽

 
Vue.directive("drag",(...rest)=>{
        //...rest展开对象
        console.log(rest);//第一个值为使用v-drag指令的当前元素,
        console.log(typeof rest);//object
    })
 
 
所以,设置第一个参数为当前的元素el(谁使用该指令,谁就是当前元素)
 
 
 
modifiers修饰符:不写,则为空,写则为a:true,b:true,,a,b为修饰符
 
value:值,并不是固定的,根据v-drag="值"来确定的
 
rewName:指令的全称
 
 
es6解构赋值
{modifier,value}获取了...rest中的modifier,value值

vue全局自定义指令实现拖拽

<!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>Document</title>
    <style>
        .box{
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
        }
    </style>
</head>
<body>
    <div id="app">
    //y轴拖拽 <div class="box" v-drag.y="show"></div>
    //x轴拖拽 <div class="box" v-drag.x="show"></div> </div> </body> </html> <script src="vue.js"></script> <script> //全局自定义指令(必须在实例之前) /* 参数1:指令的名称 参数2:指令实现的函数 */ Vue.directive("drag",(el,{value,modifiers})=>{ //el代表使用该指令的元素 el.onmousedown = function(e){ //console.log("s"); var disx = e.offsetX ; var disy = e.offsetY; //阻止浏览器的默认事件 e.preventDefault(); document.onmousemove = function(e){ var x = e.clientX - disx; var y = e.clientY - disy; //如果表达式的结果是false,就不拖拽 if(!value){ return; }
          //修饰符
if(modifiers.x){ el.style.left = x + "px"; }
          //修饰符
if(modifiers.y){ el.style.top = y + "px"; } if(!(modifiers.x && !modifiers.y) && value){ el.style.left = x + "px"; el.style.top = y + "px"; } } document.onmouseup = function(){ document.onmousemove = null; document.onmouseup = null; } } }) var vm = new Vue({ el:"#app", data:{ show:true }, method:{ } }) </script>

猜你喜欢

转载自www.cnblogs.com/SRH151219/p/10388750.html