自定义指令
星月 8/22/2022 vue
# 自定义指令
# 1. 什么是自定义指令
vue 官方提供了 v-for、v-model、v-if 等常用的内置指令。除此之外 vue 还允许开发者自定义指令。
vue 中的自定义指令分为两类,分别是:
- 私有自定义指令
- 全局自定义指令
# 2. 声明私有自定义指令的语法
在每个 vue 组件中,可以在 directives 节点下声明私有自定义指令。示例代码如下:
<script>
export default {
directives: {
// 自定义私有指令focus,在使用的时候要用 v-focus 。
focus: {
mounted(el) {
el.focus()
},
},
},
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 3. 使用自定义指令
在使用自定义指令时,需要加上 v- 前缀。示例代码如下:
<!-- 声明自定义私有指令focus,在使用的时候要用 v-focus 。 -->
<input v-focus/>
1
2
2
# 4. 声明全局自定义指令的语法
全局共享的自定义指令需要通过“单页面应用程序的实例对象”进行声明,示例代码如下:
import { createApp } from 'vue'
const app = createApp({
/* ... */
})
// 注册(对象形式的指令)
app.directive('my-directive', {
/* 自定义指令钩子 */
})
// 注册(函数形式的指令)
app.directive('my-directive', () => {
/* ... */
})
// 得到一个已注册的指令
const myDirective = app.directive('my-directive')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 5. updated 函数
mounted 函数只在元素第一次插入 DOM 时被调用,当 DOM 更新时 mounted 函数不会被触发。 updated 函数会在每次 DOM 更新完成后被调用。示例代码如下:
// 声明全局自定义指令
app.directive('focus', {
mounted(el) {
console.log('mounted')
el.focus()
},
updated(el) {
console.log('updated')
el.focus()
},
})
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
注意:在 vue2 的项目中使用自定义指令时,【 mounted 要换成 bind 】【 updated 要换成 update 】
# 6. 函数简写
如果 mounted 和updated 函数中的逻辑完全相同,则可以简写成如下格式:
app.directive('focus', (el) => {
// 在 mounted 和 updated 都会触发这个函数方法
el.focus()
})
1
2
3
4
2
3
4
# 7. 指令的参数值
在绑定指令时,可以通过“等号”的形式为指令绑定具体的参数值,示例代码如下:
// 自定义 v-color 指令
app.directive('color', (el, binding) => {
// binding.value 就是通过 = 绑定的值,在传值的时候传到这 binding.value
el.style.color = binding.value
})
1
2
3
4
5
2
3
4
5