1.自定义Vue指令
1.使用Vue.directive定义全局指令
//注册一个全局自定义指令 v-focus
Vue.directive('focus',{
//绑定元素插入到DOM中
inserted:function(el,binding){
//聚焦元素
el.focus()
}
})
参数1:指令名称(不用添加v-)
参数2:对象,存放指令相关函数(钩子函数)
-
bind:立即执行,只调用一次
-
inserted:元素插入到DOM中时执行,只执行一次
-
update:所有组件的VNode更新时执行,可能会触发多次
钩子函数的参数:
1.el:指令所绑定的元素
2.binding:一个对象
- name:指令名
value:指令的绑定值
oldvalue:指令绑定的前一个值
expression:绑定值的字符串形式
arg:传给指令的参数
2.Vue自定义私有指令
var app = new Vue(){
el:{},
data:{},
methods:{},
filters:{},
directives:{
'color':{
bind:function(){}
}
}
}
自定义指令调用过程:就近原则,私有指令和全局指令名称一致,优先调用私有指令
3.简略写法
这里省略了钩子函数,等同于把代码写到了bind和update中去
var app = new Vue(){
el:{},
data:{},
methods:{},
filters:{},
directives:{
'color':function(){}
}
}
4.实际应用
<!-- 这里颜色不能传red必须传'red' red是变量 'red'是字符串 -->
<!-- 两种写法:v-fontsize='50' v-fontsize="'50px'"-->
<div id='box' v-color="'red'" v-fontsize="'50px'">
{{msg}}
</div>
<script>
var app = new Vue({
el: '#box',
methods: {},
data: {
msg: 'Vue自定义指令操作来试试',
},
directives: {
'color': function (el, binding) {
el.style.color = binding.value
},
'fontsize': {
inserted: function (el, binding) {
console.log(binding.value);
el.style.fontSize = binding.value
}
}
}
})
</script>
1145

被折叠的 条评论
为什么被折叠?



