Vue.directive()的用法和執行個體詳解,vue.directive詳解
官網執行個體:
https://cn.vuejs.org/v2/api/#Vue-directive
https://cn.vuejs.org/v2/guide/custom-directive.html
指令定義函數提供了幾個鉤子函數(可選):
bind: 只調用一次,指令第一次綁定到元素時調用,用這個鉤子函數可以定義一個在綁定時執行一次的初始化動作。
inserted: 被繫結元素插入父節點時調用(父節點存在即可調用,不必存在於 document 中)。
update: 被繫結元素所在的模板更新時調用,而不論綁定值是否變化。通過比較更新前後的綁定值,可以忽略不必要的模板更新(詳細的鉤子函數參數見下)。
componentUpdated: 被繫結元素所在模板完成一次更新周期時調用。
unbind: 只調用一次, 指令與元素解除綁定時調用。
本人菜鳥型,看官網蒙圈,然後百度Vue.directive()的執行個體和用法,有的很高深,有的不健全,我貼上兩個簡單的demo,希望對看到的朋友有協助:
1、官網給出的demo,重新整理頁面input自動擷取焦點:
<div id="app"> <SPAN style="WHITE-SPACE: pre"> </SPAN><input type="text" v-focus/> </div> <div id="app"> <input type="text" v-focus/></div>// 註冊一個全域自訂指令 v-focus Vue.directive('focus', { // 當繫結元素插入到 DOM 中。 inserted: function (el,binding) { <SPAN style="WHITE-SPACE: pre"> </SPAN>// 聚焦元素 <SPAN style="WHITE-SPACE: pre"> </SPAN>el.focus(); } }); new Vue({ el:'#app' }); // 註冊一個全域自訂指令 v-focusVue.directive('focus', { // 當繫結元素插入到 DOM 中。 inserted: function (el,binding) { // 聚焦元素 el.focus(); }});new Vue({ el:'#app'});
2、一個拖拽的demo: 1)被拖拽的元素必須用position定位,才能被拖動;
2)自訂指令完成後需要執行個體化Vue,掛載元素;
3)inserted: 被繫結元素插入父節點時調用(父節點存在即可調用,不必存在於 document 中)。
<style type="text/css"> .one,.two{ height:100px; width:100px; border:1px solid #000; position: absolute; -webkit-user-select: none; -ms-user-select: none; -moz-user-select: -moz-none; cursor: pointer; } .two{ left:200px; } </style> <div id="app"> <div class="one" v-drag>拖拽one</div> <div class="two" v-drag>拖拽two</div> </div> <style type="text/css"> .one,.two{ height:100px; width:100px; border:1px solid #000; position: absolute; -webkit-user-select: none; -ms-user-select: none; -moz-user-select: -moz-none; cursor: pointer; } .two{ left:200px; }</style><div id="app"> <div class="one" v-drag>拖拽one</div> <div class="two" v-drag>拖拽two</div></div>[javascript] view plain copy print?Vue.directive('drag', { inserted:function(el){ el.onmousedown=function(e){ let l=e.clientX-el.offsetLeft; let t=e.clientY-el.offsetTop; document.onmousemove=function(e){ el.style.left=e.clientX-l+'px'; el.style.top=e.clientY-t+'px'; }; el.onmouseup=function(){ document.onmousemove=null; el.onmouseup=null; } } } }) new Vue({ el:'#app' });
總結
以上所述是小編給大家介紹的Vue.directive()的用法和執行個體詳解,希望對大家有所協助,如果大家有任何疑問歡迎給我留言,小編會及時回複大家的!