今天正好这个知识点有点淡忘了,就随笔一下吧:
Vue.directive(参数1,参数2)
参数1:指令名称,如"drag"
参数2:指令要实现的回调函数,其中回调函数中也有两个参数,其中:
参数1:指令绑定的元素,如 el
参数2:是一个对象,其中有两个参数(value,modifiers)
value:代表表达式要返回的结果
modifiers:指令的修饰符
话不多说,直接脑补一波实例:以拖拽为例:
<!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> *{margin:0;padding:0} .box{ width:100px; height: 100px; background: red; position: absolute;; } </style> </head> <body> <div id="app"> <div class="box" v-drag.x="show"></div> <div class="box" v-drag.y="show"></div> </div> </body> </html> <script src="vue.js"></script> <script> Vue.directive("drag",(el,{modifiers,value})=>{
//ES6中新增的解构赋值 let {x,y} = modifiers el.onmousedown = function(e){ var disX = e.offsetX; var disY = e.offsetY; e.preventDefault(); document.onmousemove = function(e){ var l = e.clientX - disX; var t = e.clientY - disY; //如果表达式的结果是false就不拖拽 if(!value)return; if(x){ el.style.left = l+"px"; } if(y){ el.style.top = t+"px"; } if((!x && !y)&&value){ el.style.left = l+"px"; el.style.top = t+"px"; } } document.onmouseup = function () { document.onmousemove = null; document.onmouseup = null; } } }) var vm = new Vue({ el:"#app", data:{ show:true } }) </script>