重学Vue的自定义指令
vue内置了许许多多指令,如 v-for,v-bind,v-show等等,但是碰到特殊场景,需要对DOM元素进行底层操作的时候,往往单靠这些内置指令是不够用的,这时候就需要用到自定义指令。
自定义指令有两种写法
对象式写法
常用的钩子函数如下
- bind : 只调用一次,元素与指令第一次绑定时调用
- inserted:当元素插入到页面那一刻调用
- update:指令所在的VNode发生改变时调用,与指令值是否改变无关
- componentUpdated:指令所在组件的 VNode 及其子 VNode 全部更新后调用。
- unbind:指令解绑时调用
// 全局注册
Vue.directive('focus',{
bind(ele,binding){
ele.style.width='200px' // 绑定时,设置元素宽度
},
inserted(ele,binding){
ele.focus() // 此时元素以及存在于页面中,可以使用focus方法
},
update(ele,binding){
ele.style.width='300px' // VNode发生改变时,设置元素宽度
}
})
// 局部指令(略)
函数式写法(简写形式,无法监听到元素被插入页面的时机)
// 全局指令 v-focus
Vue.directive('focus',function(element,binding){
// element:被指令绑定的元素
// binding: 绑定值的相关信息
element.focus() //注意:这行代码不会奏效,因为此段代码执行的时候,元素还没有被插入到页面中。
})
// 局部注册自定义指令
direcetives:{
setWidth(element,binding){
// 给元素动态绑定宽度
element.style.width = binding.value + 'px'
}
}