官網實例:
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">
<input type="text" v-focus/>
</div>
// 注冊一個全局自定義指令 v-focus
Vue.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>
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'
});