自定义局部指令
在directives
这个配置项内,可以定义多个自定义指令,与data同级
定义指令注意的点:
- v- 不需要写
- Vue官方建议,指令名都小写,如果是多个单词,用‘-’连接
- 语法:
指令名:回调函数
回调函数接受参数:
el
:指令所绑定的元素,可以用来直接操作 DOMbinding
:一个对象,包含和自定义的指令有关的信息name
:指令名,不包括v-
前缀value
:指令的绑定值,例如:v-my-directive="1 + 1"
中,绑定值为2
- …更多可参考vue2官网 vue2自定义指令
回调函数执行时机:
- 执行时机1:标签和指定第一次绑定的时候
- 执行时机2:当模版被重新解析的时候
写法一 :函数式写法
let vm = new Vue({
el: '#root',
data(){
return {
}},
directives: {
// 写法一 :函数式写法
// 指令名:回调函数
"text-danger": function (element, binding) {
// 与属性绑定,且将文字颜色替换为红色
element.innerText = binding.value;
element.style.color = "red";
},
}
})
写法二、 对象式
let vm = new Vue({
el: '#root',
data(){
return {
}},
directives: {
// 写法二、 对象式
// 指令名:{}
"bind-blue": {
// 对象中有3个固定写法的函数,这三个函数在不同的时机会被调用
// 像这种在特定的时间节点调用特定的函数,这种函数叫钩子函数
// bind() 元素与指令初次绑定时执行
bind(element, binding) {
element.value = binding.value;
},
// inserted() 元素被插入页面之后执行
inserted(element, binding) {
element.parentNode.style.backgroundColor = "green";
},
//update() 当模版重新解析的时候,会被执行
update(element, binding) {
element.value = binding.value;
},
},
}
})
自定义全局指令
只是配置项的写法不一样,为全局配置写法,写在Vue实例上面,其它和局部自定义属性一样
语法:
Vue.directive(
)
函数写法:
// 函数式 Vue.directive('指令名',回调函数)
Vue.directive('text-danger',function(element,binging){
element.innerText=binging.value
element.style.color='red'
})
对象写法:
// 对象式 Vue.directive('指令名',{bind(){},inserted(){},update(){}})
Vue.directive('bind-blue',{
bind(element,binging){
element.value=binging.value
},
inserted(element,binging){
element.parentNode.style.backgroundColor='blue'
},
update(element,binging){
element.value=binging.value
}
})