Vue.directive 自定义指令的入口
基本使用
app.vue 中设置一个h1标签
<h1 v-color='"red"'>自定义指令red</h1>
<h1 v-color='"orange"'>自定义指令orange</h1>
<h1 v-size='"60px"'>自定义指令 显示隐藏</h1>
v-color、v-size 时自定义指令的名称,red orange 60px 是属性值
在main.js中设置指令
Vue.directive('color',(el,binding)=>{
el.style.color = binding.value
})
Vue.directive('size',(el,binding)=>{
el.style.fontSize = binding.value
})
使用自定义指令是必须加上 v-
Vue.directive 接收两个参数 第一个参数是自定义指令的名称
第二个参数可以是函数也可以是对象
如果是函数 函数接收2个参数 第一个返回元素名称 第二个返回一个对象,内部有需要的参数
设置的是<h1 v-color='5>3'>自定义指令red</h1>
返回结果
-
expression :是一个表达式,返回的是 设置给自定义指令的值
-
modifiers:自定义指令如果有修饰符返回的是 布尔值对象 <h1 v-color.stop.self='5>3'>自定义指令red</h1>
-
name:自定义指令名称
-
rawName:设置自定义指令名称
-
value:自定义指令返回值
第二个参数是对象,内部是指令清单的函数钩子
例:显示与隐藏的切换
Vue.directive('isshow',{
bind:(el)=>{
console.log('bind',el)
},
inserted:(el,binding)=>{
console.log("inserted",el,binding)
//初始化隐藏
if(!binding.value){
el.style.display = "none"
}
},
update:(el,binding)=>{
console.log('update',el,binding)
if(!binding.value){
el.style.display = "none"
}else{
el.style.display = "block"
}
},
componentUpdated:(el,binding)=>{
console.log('componentUpdate',el,binding)
},
unbind:(el)=>{
console.log("unbind",el)
}
})
- bind:只调用一次, 指的是指令第一次绑定到元素的时候调用 ----------------- 初始化设置样式时使用
- inserted:只调用一次,节点插入到父节点调用 ------ 有逻辑判断的时候使用
- update:数据更新是调用,在虚拟DOM跟新之前
-
componentUpdated:数据跟新是调用,在虚拟DOM更新后调用
-
unbind:指令卸载时调用
<template>
<div>
<h1 v-color='5>3'>自定义指令red</h1>
<h1 v-color='"orange"'>自定义指令orange</h1>
<h1 v-isshow="isShow" v-size='"60px"'>自定义指令 显示隐藏</h1>
<button @click="show"> 显示隐藏</button>
</div>
</template>
<script>
export default {
data(){
return{
isShow:false
}
},
methods:{
show(){
this.isShow = !this.isShow
}
}
}
</script>