1. 程式人生 > >Vue.directive全域性自定義指令案例

Vue.directive全域性自定義指令案例

今天正好這個知識點有點淡忘了,就隨筆一下吧:

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>