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>