0%

【017】Vue全局API学习:Vue.directive

用法

注册或获取全局指令。

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script>
</head>
<body>
<div id="app">
<input v-focus />
</div>
<script type="text/javascript">
// 注册一个全局自定义指令 `v-focus`
Vue.directive('focus', {
// 当被绑定的元素插入到 DOM 中时……
inserted(el) {
// 聚焦元素
el.focus();
}
})
var vm = new Vue({ el: '#app' });
</script>
</body>
</html>

在浏览器中运行上面的代码,可以看到文本框在页面加载时自动聚焦了。

自定义指令的生命周期(钩子函数)

钩子函数说明:

函数 说明
bind 只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置
inserted 被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)
update 所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前。指令的值可能发生了改变,也可能没有。但是你可以通过比较更新前后的值来忽略不必要的模板更新
componentUpdated 指令所在组件的 VNode 及其子 VNode 全部更新后调用
unbind 只调用一次,指令与元素解绑时调用

看钩子函数说明后,再来看个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script>
</head>
<body>
<div id="app">
<div v-demo="'demo'">当前数字:{{ num }}</div>
<button @click="num++">累加</button>
<button @click="destroy">解绑</button>
</div>
<script type="text/javascript">
Vue.directive('demo', {
bind(el, bingind){
alert('bind:' + bingind.value);
},
inserted(){
alert('inserted');
},
update(){
alert('update');
},
componentUpdated(){
alert('componentUpdated');
},
unbind(){
alert('unbind');
}
});
var vm = new Vue({
el: '#app',
data() {
return {
num: 0
}
},
methods: {
// 解绑
destroy() {
this.$destroy();
}
}
});
</script>
</body>
</html>

当浏览器加载完成时,页面会先弹出bind:demodemov-demo="'demo'"中的值,关闭弹出框后,继续弹出inserted,关闭后,首次的钩子函数执行完成。
接着我们点击累加按钮,点击完成后,页面弹出update,关闭后继续弹出componentUpdated,到此为止,点击按钮后触发的钩子函数执行完成。
最后,我们点击解绑按钮,页面弹出unbind,紧接着试着点击累加按钮,发现没有任何效果,说明解绑成功。