-Vue的指令以v-开头,除了官方的指令,有时候我们想要自己全局设定一些自定义指令,方便全局运用。
Vue.directive('name',{
inserted:function(el){
el.focus();
}
})
钩子函数
Vue.directive('name',{
bind:function(el){
el.style.color = "red";
}
})
简写模式
-在很多时候,你可能想在 bind 和 update 时触发相同行为,而不关心其它的钩子。比如这样写:
Vue.directive("fontsize",function(el,binding){
console.log(typeof(binding.value),binding);
el.style.fontSize = binding.value + "px";
})
自定义指令可以配合data变量,进而形成动态的样式
<div v-fontsize='fs'>一起摇摆</div>
-在脚手架中如何引用自定义指令?
1.建一个js文件
2.在里面定义指令以及函数
import Vue from 'vue'
Vue.directive('focus',{
inserted:function(el){
console.log(1);
el.focus();
}
})
Vue.directive('title',{
bind:function(el){
el.style.color = "blue";
el.classList.add("animated", "bounceInRight");
},
inserted:function(el){
}
})
Vue.directive("fontsize",function(el,binding){
console.log(typeof(binding.value),binding);
el.style.fontSize = binding.value + "px";
})
3.在main.js引入js文件,就可以在全局使用自定义指令了。
网友评论