官网:https://cn.vuejs.org/v2/guide/custom-directive.html
v-if
等是内置的指令, 在这里研究自定义指令
局部自定义指令
在directives
中定义,在一个组件中定义的,只能在这一个组件中使用 ;
定义命令:
directives:{
//自定义指令color,el是这个标签,binding是传入的值
color:function(el,binding){
el.style.color=binding.value
}
}
//自定义了 color
调用命令:
<p v-color="'red'">hello123</p>
//使用 v-color 调用
传入的值使用"' '"包裹着
全局自定义指令
只需要把自定义的指令放到根节点的组件中定义即可
更细致定义
一个自定义对象可以定义几个钩子函数,没有声明的时候,默认是bind
和update
字段 | 功能 |
---|---|
bind : | 只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。 |
inserted | 被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)。 |
update | 所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前。指令的值可能发生了改变,也可能没有。但是你可以通过比较更新前后的值来忽略不必要的模板更新 (详细的钩子函数参数见下)。 |
componentUpdated | 指令所在组件的 VNode 及其子 VNode 全部更新后调用 |
unbind | 只调用一次,指令与元素解绑时调用。 |
//自定义指令color
color:{
bind:function(el,binding){
el.style.color=binding.value
},
inserted:function(el){//不需要值
}
}
案例:input获取光标
//定义字段
focus:{
inserted:function(el,binding){
el.focus()
}
}
//调用
<input type="text" v-focus />