5.6 自定义指令:
我们可以通过自定义来定义一些我们需要但Vue不提供的指令:
Vue自定义指令的两种方式:
全局定义:
完整写法:
Vue.directive(‘指令名’,{
bind(element,binding){},
inserted(element,binding){},
update(element,binding){},
});
或:
函数写法:
Vue.directive(‘指令名’,function(element,binding){})
局部定义:
函数写法:
new Vue({
directives:{
‘指令名’(element,binding){
}
}
})
或
完整写法:
new Vue({
directives:{
bind(element,binding){},
inserted(element,binding){},
update(element,binding){},
}
})
两个参数的含义:
element:与指令进行绑定的元素;
如:<input v-fbind:value="n" type="text">
,element的值为<input type="text">
;
binding:一个包含指令信息的对象,里面最重要的字段是value
配置对象中常用的三个回调:
bind:指令与元素成功绑定时调用;
inserted:指令所在元素被插入页面时调用;
update:指令所在的模板被重新解析时调用;
注意事项:
1.在定义时不加v-,但在使用时要加v-;
2.指令名如果是多个单词,单词之间要用-连接,如“get-max”,不能使用驼峰命名;
例子1:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="../js/vue.js" type="text/javascript"></script>
<title>自定义指令</title>
</head>
<body>
<div class="root">
<h1>数字是 <span v-text="n"></span></h1>
<h1>放大十倍的数字是 <span v-big="n"></span></h1>
<button @click="n++">点我n+1</button>
</div>
<script type="text/javascript">
Vue.config.productionTip = false
//Vue instance
const x = new Vue({
// el:document.getElementById('root') the same
el:".root",
data:{
n:1
},
directives:{
//big函数何时会被调用,1:指令与元素成功绑定时(一上来),2:指令所在的模板被重新解析时
big(element,binding) {
element.innerText = binding.value * 10
}
},
})
</script>
</body>
</html>
例子2:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="../js/vue.js" type="text/javascript"></script>
<title>自定义指令2</title>
</head>
<body>
<div class="root">
<input :value="n" type="text">
<input v-fbind:value="n" type="text">
<button @click="n++">点我加一</button>
</div>
<script type="text/javascript">
Vue.config.productionTip = false
//全局的directive
Vue.directive('fbind',{
//指令与元素成功绑定时
bind(element,binding){
console.log(this) //注意在自定义指令中的this都是window
element.value = binding.value
},
//指令所在元素被插入页面时
inserted(element,binding){
element.focus()
},
//指令所在的模板被重新解析时
update(element,binding){
element.value = binding.value
}
})
//Vue instance
const x = new Vue({
// el:document.getElementById('root') the same
el:".root",
data:{
n:10
},
//局部directives
directives:{
fbind:{
//指令与元素成功绑定时
bind(element,binding){
console.log(element,binding) //注意在自定义指令中的this都是window
element.value = binding.value
},
//指令所在元素被插入页面时
inserted(element,binding){
element.focus()
},
//指令所在的模板被重新解析时
update(element,binding){
element.value = binding.value
},
}
}
})
</script>
</body>
</html>