自定义指令
- 全局自定义指令
- 局部自定义指令
- 指令的钩子函数(一共有5个)
- bind : 指令和元素第一次绑定的时候调用
- inserted : 指令绑定的元素插入父节点的时候调用
- update : 指令绑定的元素自身, 或是他的内容(子节点)发生改变的时候出发
- componentUpdated : 指令绑定的组件自身, 或是他的内容(子节点)发生改变的时候出发
- unbind : 指令和元素第一次解绑是调用
- 指令的钩子函数(一共有5个)
- 指令的钩子函数的参数
- el 当前元素
- binding 当前指令的所有信息
- vNode 当前指令绑定的虚拟节点
- oldVnode 指令绑定前的虚拟节点
directive-全局
<body>
<div id="app">
<div v-append v-if = "flag">
{{ msg }}
</div>
<input type="text" v-focus>
</div>
</body>
<script>
/*
业务:
当我打开页面的时候, input框自动获得焦点?
*/
// Vue.directive(指令的名称,指令的配置项(钩子函数))
Vue.directive('focus',{
/* 钩子函数 */
bind () {
console.log('指令和元素第一次绑定')
},
inserted ( el, binding, vnode, oldVnode ) {
console.log('el',el)
console.log('binding',binding)
console.log('vnode',vnode)
console.log('oldvnode',oldVnode)
el.focus()
el.style.background = 'red'
}
})
Vue.directive('append',{
inserted (el) {
var p = document.createElement('P')
p.innerHTML = '你好吗'
el.appendChild(p)
},
update () {
console.log('update')
},
componentUpdated () {
console.log( 'componentUpdated' )
},
unbind ( el ) {
console.log( 'unbind' )
}
})
new Vue({
el: '#app',
data: {
msg: 'hello 指令',
flag: true
}
})
</script>
directive-局部
<body>
<div id="app">
<input type="text" v-focus.yyb = 'yyb'>
</div>
</body>
<script>
/*
推理:
v-for = 'item in list'
*/
new Vue({
el: '#app',
data: {
yyb: '复仇者联盟4上线',
item: 10
},
directives: {
'focus': {
inserted ( el,binding ) {
console.log( 'binding' , binding)
if( binding.modifiers.junge ){
el.style.background = 'red'
}else{
el.style.background = 'yellow'
}
el.focus()
}
}
}
})
</script>