1. 自定义全局指令
1.1 自定义全局指令,让文本框获取焦点
自定义一个指令"v-focus"
<input type="text" class="form-control" v-model="keywords" id="search" v-focus>
使用Vue.directive()定义全局指令。
其中,参数1是指令名称,在定义的时候,指令名称前面不需要加"v-"前缀,在调用的时候才用。
参数2是一个对象,对象包含一些指令相关的函数。
Vue.directive('focus',{
bind:function(el){ //每当指令绑定到元素上的时候,会立即执行这个bind函数,只执行一次
//注意:在每个函数中,第一个参数永远是el,表示被绑定了指令的那个元素,这个el参数,是一个原声js对象
//在指令刚绑定了元素的时候,还没有插入到DOM中去,这时候调用focus方法没有作用
//因为一个元素,只有插入到DOM之后,才能获取焦点
//el.focus()
},
inserted:function(el){ //元素插入到DOM中的时候,会执行inserted函数,只触发一次
el.focus()
},
updated:function(el){ //当VNode更新的时候,会执行updated函数,可能会触发多次
}
})
页面打开后,输入光标自动定位到输入框。
1.2 自定义全局指令,设置文字样式
定义一个“v-color”指令
<input type="text" class="form-control" v-model="keywords" id="search" v-focus v-color>
//自定义一个设置字体颜色的指令
Vue.directive('color',{
//样式,只要通过指令绑定了元素,不管这个元素有没有被插入到页面中去,这个元素肯定是有了一个内联样式
//当元素显示到页面中去的时候,浏览器的渲染引擎必然会解析样式,应用给这个元素
bind:function(el){
//和样式相关的操作,一般都可以在bind中执行
el.style.color='red'
}
})
1.3 自定义指令的时候,使用传递的参数值
代码示例:
<input type="text" class="form-control" v-model="keywords" id="search" v-color="'blue'">
Vue.directive('color',{
bind:function(el,binding){
console.log(binding.value)
console.log(binding.expression)
el.style.color=binding.value
}
})
效果:
2. 自定义私有指令
<div id="app2">
<h3 v-fontweight="900">{{dt}}</h3>
</div>
<script>
var vm2=new Vue({
el:'#app2',
data:{
dt:new Date()
},
methods:{},
directives:{
'fontweight':{
bind:function(el,binding){
el.style.fontWeight=binding.value
}
}
}
})
</script>
3. 指令函数的简写形式
大多数情况下,我们可能想在bind和update钩子上做重复动作,并不想关心其他的钩子函数,可以这样写:
<div id="app2">
<h3 v-fontweight="900" v-fontsize="30">{{dt}}</h3>
</div>
<script>
var vm2=new Vue({
el:'#app2',
data:{
dt:new Date()
},
methods:{},
directives:{
'fontweight':{
bind:function(el,binding){
el.style.fontWeight=binding.value
}
},
'fontsize':function(el,binding){ //注意:这个function等同于把代码写到bind和update中去。
el.style.fontSize=parseInt(binding.value)+'px'
}
}
})
</script>