Vue3 自定义指令完全指南
目录
基本概念
在Vue3中,自定义指令是用于直接操作DOM的重要工具。相比Vue2,Vue3的指令系统进行了优化和简化。
生命周期钩子
钩子名称 | 对应Vue2名称 | 触发时机 |
---|---|---|
created | bind | 元素属性绑定前 |
beforeMount | inserted | 元素插入父节点前 |
mounted | - | 元素插入父节点后 |
beforeUpdate | update | 组件更新前 |
updated | componentUpdated | 组件及子组件更新后 |
beforeUnmount | unbind | 元素卸载前 |
unmounted | - | 元素卸载后 |
指令注册方式
全局注册
javascript
// main.js
const app = createApp(App)
app.directive('focus', {
mounted(el) {
el.focus()
}
})
局部注册
javascript
export default {
directives: {
highlight: {
mounted(el, binding) {
el.style.backgroundColor = binding.value || 'yellow'
}
}
}
}
常用应用场景
1. 自动聚焦
javascript
// 使用
<input v-focus>
// 实现
app.directive('focus', {
mounted(el) {
el.focus()
}
})
2. 权限控制
javascript
// 使用
<button v-permission="['admin']">删除</button>
// 实现
app.directive('permission', {
mounted(el, binding) {
const roles = ['user', 'editor', 'admin']
if (!binding.value.includes(roles.current)) {
el.parentNode.removeChild(el)
}
}
})
3. 防抖指令
javascript
// 使用
<button v-debounce:click="submitForm">提交</button>
// 实现
app.directive('debounce', {
mounted(el, binding) {
let timer = null
el.addEventListener(binding.arg, () => {
clearTimeout(timer)
timer = setTimeout(() => {
binding.value()
}, 500)
})
}
})
进阶技巧
动态参数传递
javascript
// 使用
<div v-pin:[direction]="200"></div>
// 实现
app.directive('pin', {
mounted(el, binding) {
el.style.position = 'fixed'
const direction = binding.arg || 'top'
el.style[direction] = binding.value + 'px'
}
})
Composition API 结合
javascript
import { useScroll } from './scrollComposable'
app.directive('scroll', {
mounted(el, binding) {
const { start, stop } = useScroll(binding.value)
el._scrollHandler = { start, stop }
start()
},
unmounted(el) {
el._scrollHandler.stop()
}
})
注意事项
- 避免过度使用:优先使用组件化方案
- 参数验证 :使用
binding.value
前进行类型检查 - 性能优化:及时在unmounted阶段清理副作用
- 命名规范 :使用小写字母+连字符格式(如
v-custom-directive
) - 浏览器兼容:谨慎使用新API,必要时添加polyfill
总结
场景 | 推荐指令类型 | 示例 |
---|---|---|
DOM操作 | 自定义指令 | v-tooltip |
全局功能 | 全局指令 | v-permission |
复杂交互 | 组合式指令 | v-draggable |
简单样式修改 | 类绑定 | :class="..." |
通过合理使用自定义指令,可以使代码更简洁、维护性更好,但要注意保持指令的单一职责原则。