Vue
中功能的复用有,组件(components
)、继承(extends
)、混入(mixins
)、过滤器(filters
)和自定义指令(directives
),下面看自定义指令的使用。
一、使用场景
主要用于对于DOM的操作,比如:文本框聚焦,节点位置控制、防抖节流、权限管理、复制操作等功能
二、钩子函数
bind
:只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。inserted
:被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)。update
:所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前。指令的值可能发生了改变,也可能没有。但是你可以通过比较更新前后的值来忽略不必要的模板更新。componentUpdated
:指令所在组件的 VNode 及其子 VNode 全部更新后调用。unbind
:只调用一次,指令与元素解绑时调用。
三、钩子函数参数
el
:指令所绑定的元素,可以用来直接操作 DOM。binding
:一个对象,包含以下 property:name
:指令名,不包括v-
前缀。value
:指令的绑定值,例如:v-my-directive="1 + 1"
中,绑定值为2
。oldValue
:指令绑定的前一个值,仅在update
和componentUpdated
钩子中可用。无论值是否改变都可用。expression
:字符串形式的指令表达式。例如v-my-directive="1 + 1"
中,表达式为"1 + 1"
。arg
:传给指令的参数,可选。例如v-my-directive:foo
中,参数为"foo"
。modifiers
:一个包含修饰符的对象。例如:v-my-directive.foo.bar
中,修饰符对象为{ foo: true, bar: true }
。
vnode
:Vue 编译生成的虚拟节点。oldVnode
:上一个虚拟节点,仅在update
和componentUpdated
钩子中可用。
四、动态指令参数
指令的参数可以是动态的。例如,在 v-mydirective:[argument]="value"
中,argument
参数可以根据组件实例数据进行更新!这使得自定义指令可以在应用中被灵活使用。
五、实际例子
1、自动聚焦
利用inserted钩子函数
:
Vue.directive("focus", {
inserted: function(el) {
el.focus();
}
});
new Vue({
el: "#app",
template: `<input v-focus>`
});
在当前节点插入到父元素的钩子函数中,通过el.focus
的方式进行input
的聚焦处理。
2、固定位置
利用钩子函数参数
:
Vue.directive('pin', {
bind: function (el, binding, vnode) {
el.style.position = 'fixed'
el.style.top = binding.value + 'px'
}
})
new Vue({
el: `#app`,
template: `<div><p v-pin="200">我被固定到距离页面顶部200px的位置喽</p>`
})
当前例子中,在bind
钩子函数中,将节点的定位属性设置为fixed
后,再从binding
中获取其值,作为距离页面顶部的偏移量。
3、根据方向固定位置
利用动态指令参数
:
Vue.directive('pin', {
bind: function (el, binding, vnode) {
el.style.position = 'fixed'
el.style[binding.arg] = binding.value + 'px'
}
})
new Vue({
el: `#app`,
template: `<p v-pin:[direction]=[positionSite]>我被固定到距离页面{{directionMap[direction]}}200px的位置喽</p>`,
data() {
return {
direction: 'left',
positionSite: 100,
directionMap: {
left: '左侧',
top: '顶部',
bottom: '底部',
right: '右侧'
},
}
}
})
当前例子中的偏移方向和偏移距离都通过更为灵活的动态参数的方式传入。
总结
自定义指令是通过其提供的钩子函数和参数值来实现的。