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