<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="../assets/js/vue.js"></script>
<title>案例</title>
</head>
<body>
<div id="app">
<div v-jspang="color" id="demo">
{{num}}
</div>
<div>
<button @click="add">Add</button>
</div>
</div>
<script type="text/javascript">
Vue.directive('jspang',function(el,binding,vnode){
el.style='color:'+binding.value;
});
var app=new Vue({
el:'#app',
data:{
num:10,
color:'red'
},
methods:{
add:function(){
this.num++;
}
}
})
</script>
</body>
</html>
自定义指令中传递的三个参数
el: 指令所绑定的元素,可以用来直接操作DOM。
binding: 一个对象,包含指令的很多信息。
vnode: Vue编译生成的虚拟节点。
自定义指令的生命周期
自定义指令有五个生命周期(也叫钩子函数),分别是 bind,inserted,update,componentUpdated,unbind
bind:只调用一次,指令第一次绑定到元素时调用,用这个钩子函数可以定义一个绑定时执行一次的初始化动作。
inserted:被绑定元素插入父节点时调用(父节点存在即可调用,不必存在于document中)。
update:被绑定于元素所在的模板更新时调用,而无论绑定值是否变化。通过比较更新前后的绑定值,可以忽略不必要的模板更新。
componentUpdated:被绑定元素所在模板完成一次更新周期时调用。
unbind:只调用一次,指令与元素解绑时调用。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
bind
:
function
(
)
{
//被绑定
console
.
log
(
'1 - bind'
)
;
}
,
inserted
:
function
(
)
{
//绑定到节点
console
.
log
(
'2 - inserted'
)
;
}
,
update
:
function
(
)
{
//组件更新
console
.
log
(
'3 - update'
)
;
}
,
componentUpdated
:
function
(
)
{
//组件更新完成
console
.
log
(
'4 - componentUpdated'
)
;
}
,
unbind
:
function
(
)
{
//解绑
console
.
log
(
'1 - bind'
)
;
}
|
实例:
// 注册一个全局自定义指令 v-focus
Vue.directive('focus', {
// 当绑定元素插入到 DOM 中。
inserted: function (el) {
// 聚焦元素
el.focus()
}
})