vue中的自定义指令
注册一个局部指令
<template>
<div>
<h1>{{name}}</h1>
<p @click='updateEl'>更新</p>
<input type="text" v-focus>
</div>
</template>
<script>
export default {
data () {
return {
name: '初始化'
}
},
methods:{
updateEl(){
setTimeout(()=>{
this.name = '初始化数据'
}, 3000)
}
},
directives: {
'focus': {
inserted: (el) => {
// el指的是当前绑定的元素
console.log('被绑定元素插入父节点时调用')
el.focus()
},
bind: (el,binding) => {
console.log(binding, '钩子函数的参数')
// 只调用一次, 指令第一次绑定到元素时调用, 用这个钩子函数可以定义一个在绑定时执行一次的初始化动作
el.value = '你好'
},
update: () => {
// 被绑定元素所在的模板更新时调用, 而不论绑定值是否变化。通过比较更新前后的绑定值, 可以忽略不必要的模板更新,当上面更新数据改变时会触发这个事件
console.log('我在的组件更新了!')
},
componentUpdated: () => {
// 被绑定元素所在模板完成一次更新周期时调用
console.log('我在的组件完成一次更新更新周期时调用')
},
unbind: () => {
// 元素解除绑定时调用
console.log('我和指令解除绑定了')
}
}
}
}
</script>
<style scoped lang="scss">
</style>
注册全局的指令
可以把这段代码写在main.js中
Vue.directive('fontcolor',{
inserted: (el)=> {
el.style.color = 'orange'
}
})
在组件中调用
<span v-fontcolor>全局</span>