自定义指令
Vue.directive("指令名",{});
-
Vue.directive内部钩子函数
1). bind(){} // 绑定元素时执行,只执行一次(常用)
2). inserted(){} // 当被绑定元素插入到dom时执行
3). update(){} // 当被绑定元素更新时执行
4). componentUpdated(){} // 被绑定元素模版完成一次周期更新时执行
5). unbind(){} // 当被绑定元素解除时执行 -
Vue.directive钩子函数参数介绍
1). el // 返回被绑定元素的dom对象
2). binding // 返回绑定元素的各种参数object
ps:binding实例方法:
// 钩子函数的参数介绍
html调用方法:<p v-world:foo.add.dele="hehe">{{msg}}</p>
Vue.directive("world",{
bind(el, binding){
// console.log(el); // el:返回被绑定元素的dom对象
console.log(binding);
/* binding 返回的各种参数
{
name: "world", // 返回自定义指令的名字
rawName: "v-world:foo.add.dele", // 返回自定义指令的调用
value: "eeeeeeeeee", // 返回指令绑定的值
expression: "hehe", // 返回指令绑定的值的名字
arg: "foo", // 返回调用时参数foo的名字
…
}
arg: "foo"
expression: "hehe"
add: true // 指令的修饰符
dele: true
name: "world" // 指令的修饰符
rawName: "v-world:foo.add.dele"
value: "eeeeeeeeee"
*/
}
})
- Vue.directive第二种使用方法,直接传入一个函数,但是只会执行bing()和update()
html调用:<p v-onefn>{{msg}}</p>
// 传入一个函数的方法 只会执行bing()和update()钩子函数,另外指令名还不能驼峰式写法
Vue.directive("onefn",function(){
alert("directive传入一个函数的方法")
})
- Vue.directive局部写法
局部写法式写在vue实例内部,而且是写为:directives,多加了一个s
局部用法实例:
html调用:<input type="text" v-model="msg" v-inpfocus>
var vm = new Vue({
el: "#app",
data:{
msg:"hello vue!",
},
methods:{
},
directives:{ // 自定义指令局部写法,局部写法记得加s为directives 全局为 Vue.directive
inpfocus:{
inserted(el){
el.focus();
}
}
}
});