Vue.directive
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>自定义指令</title>
</head>
<body>
<div id='app'>
<h1 v-hello>{{msg}}</h1>
<button @click='change'>改变msg内容</button>
</div>
<script src='./vue.js'></script>
<script>
Vue.directive('hello',{
bind(){ // 指令第一次绑定到元素的时候执行,且只执行一次,一般用于执行初始化操作
console.log('bind')
},
inserted(){ // 当被绑定的元素插入到DOM中时执行
console.log('inserted')
},
update(){ // 当被绑定的元素所在模版更新时执行
console.log('update')
},
componentUpdated(){ // 一般不怎么用,表示被绑定元素所在模板完成一次更新周期时调用,个人感觉效果与update有点重合
console.log('componentUpdated')
},
unbind(){ // 指令与被绑定的元素解绑时使用,只调用一次
console.log('unbind')
}
})
var vm = new Vue({
el:'#app',
data:{
msg:'hello world'
},
methods:{
change(){
this.msg = this.msg.split('').reverse().join('')
}
}
})
</script>
</body>
</html>
其中bind,unbind,update,inserted,componentUpdated是钩子函数.钩子函数默认有两个参数. el , binging .其中 el 表示当前指令所绑定的元素. binging 是一个对象.binging.name指的是指令名 . binging.value 指的是指令指定的值.binging.expression.绑定的值的字符串形式.binging.args.传线指定的参数. binging.modifiers 指令接收到的修饰符,以对象形式接收.