Files
blog-press/docs/Web/Vue/Vue3-Directive.md
2026-06-05 15:53:29 +08:00

80 lines
1.9 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: Vue3自定义指令
date: 2026-06-05
---
# 一、概念
  自定义指令Directive 是 Vue 提供的一种机制,用于直接操作 DOM封装可复用的底层 DOM 行为。它是对模板能力的补充当现有模板语法v-if / v-bind / v-on不够用时就可以用指令。
# 二、简单示例
  注册:
```ts
app.directive('demo', {
mounted(el, binding) {
console.log(el, binding)
}
})
```
  使用:
```vue
<div v-demo="'hello'"></div>
```
&emsp;&emsp;使用该指令,就会触发打印效果。
# 三、生命周期
| 钩子 | 说明 |
| ----- | ----- |
| created | 绑定前 |
| beforeMount | 元素挂载前 |
| mounted | 元素已挂载 |
| beforeUpdate | 更新前 |
| updated | 更新后 |
| beforeUnmount | 卸载前 |
| unmounted | 卸载后 |
# 四、参数
&emsp;&emsp;mounted(el, binding, vnode, prevVnode)
| 参数 | 说明 |
| ----- | ----- |
| el | 当前 DOM 元素 |
| binding.value | 指令绑定的值 |
| binding.arg | 参数 |
| binding.modifiers | 修饰符 |
| vnode | 虚拟节点 |
# 五、封装
&emsp;&emsp;`src`目录新建`directives/**.ts`,定义指令:
```ts
import { useAuthStore } from '@/stores/auth'
export default {
mounted(el, binding) {
const authStore = useAuthStore()
const permission = binding.value
const hasPermission = authStore.currentUser?.permission?.includes(permission)
if (!hasPermission) {
el.parentNode?.removeChild(el)
}
}
}
```
&emsp;&emsp;该指令根据用户权限控制DOM是否显示。
&emsp;&emsp;然后在`main.ts`中注册指令:
```ts
import permissionDirective from '@/directives/permission'
app.directive('permission', permissionDirective)
```
&emsp;&emsp;最后在需要的元素中加上`v-permission=""`即可。
::: tip
自定义指令只做DOM相关的事情比如隐藏DOM禁止点击、修改样式等等。
:::