学习笔记: 自定义指令
自定义指令的注册方法分为全局注册和局部注册,好比注册一个v-focus
指令,用于在<input>
、<textarea>
元素初始化时自动得到焦点,两种写法分别是:html
//全局注册 Vue.directive('focus', {}); //局部注册 new Vue({ el: '#app', directives: { focus: {} } });
自定义指令的选项是由几个钩子函数组成,每一个都是可选的:node
bind
:只调用一次,指令第一次绑定到元素时调用,用这个钩子函数能够定义一个在绑定时执行一次的初始化动做。inserted
:被绑定元素插入父节点时调用(父节点存在便可调用,没必要存在于document
中)。update
:被绑定元素所在的模板更新时调用,而不论绑定值是否变化。经过比较更新先后的绑定值,能够忽略没必要要的模板更新。componentUpdate
:被绑定元素所在模板完成一次更新周期时调用。unbind
:只调用一次,指令与元素解绑时调用。能够根据需求在不一样的钩子函数内完成逻辑代码。在元素插入父节点时就调用,用到的最好是inserted
。git
<div id="app"> <input type="text" v-focus> </div> Vue.directive('focus', { inserted(el) { el.focus(); } }); new Vue({ el: '#app', });
打开页面,input
输入框自动得到焦点,成为可输入状态。github
每一个钩子函数都有几个参数可用:express
el
指令所绑定的元素,能够用来直接操做DOMbinding
一个对象,包含如下属性:数组
name
指令名,不包括v-
前缀value
指令的绑定值oldValue
指令绑定的前一个值,仅在update
和componentUpdate
钩子中可用。不管值是否改变均可用。expression
绑定值的字符串形式。arg
传给指令的参数。modifiers
一个包含修饰符的对象。vnode
Vue编译生成的虚拟节点。oldVnode
上一个虚拟节点仅在update
和componentUpdate
钩子中可用。<p data-height="265" data-theme-id="0" data-slug-hash="QxKQqY" data-default-tab="html,result" data-user="whjin" data-embed-version="2" data-pen-title="Vue-自定义指令" class="codepen">See the Pen Vue-自定义指令 by whjin (@whjin) on CodePen.</p>
<script async src="https://static.codepen.io/ass...;></script>app
若是须要多个值,自定义指令能够传入一个JavaScript对象字面量。frontend
<div id="app"> <div v-test="{msg:'hello',name:'Andy}"></div> </div>
v-time
<p data-height="265" data-theme-id="0" data-slug-hash="wXoMpg" data-default-tab="html,result" data-user="whjin" data-embed-version="2" data-pen-title="Vue-实时时间转换指令" class="codepen">See the Pen Vue-实时时间转换指令 by whjin (@whjin) on CodePen.</p>
<script async src="https://static.codepen.io/ass...;></script>async
Time.getFormatTime()
方法就是自定义指令v-time
所须要的,入参为毫秒级时间戳,返回已经整理好时间格式的字符串。函数
在bind
钩子里,将指令v-time
表达式的值binding.value
做为参数传入TimeFormatTime()
方法获得格式化时间,再经过el.innerHTML
写入指令所在元素。定时器el.__timeout__
每分钟触发一次,更新时间,而且在unbind
钩子里清除掉。
总结:在编写自定义指令时,给DOM绑定一次性事件等初始动做,建议在bind
钩子内完成,同时要在unbind
内解除相关绑定。