Vue3 自定义指令完全指南
目录
- 基本概念
- 指令注册方式
- 常用应用场景
- 注意事项
基本概念
在Vue3中,自定义指令是用于直接操作DOM的重要工具。相比Vue2,Vue3的指令系统进行了优化和简化。
生命周期钩子
created | bind | 元素属性绑定前 |
beforeMount | inserted | 元素插入父节点前 |
mounted | – | 元素插入父节点后 |
beforeUpdate | update | 组件更新前 |
updated | componentUpdated | 组件及子组件更新后 |
beforeUnmount | unbind | 元素卸载前 |
unmounted | – | 元素卸载后 |
指令注册方式
全局注册
// main.js
const app = createApp(App)
app.directive('focus', {
mounted(el) {
el.focus()
}
})
局部注册
export default {
directives: {
highlight: {
mounted(el, binding) {
el.style.backgroundColor = binding.value || 'yellow'
}
}
}
}
常用应用场景
1. 自动聚焦
// 使用
<input v–focus>
// 实现
app.directive('focus', {
mounted(el) {
el.focus()
}
})
2. 权限控制
// 使用
<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. 防抖指令
// 使用
<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)
})
}
})
进阶技巧
动态参数传递
// 使用
<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 结合
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()
}
})
注意事项
总结
DOM操作 | 自定义指令 | v-tooltip |
全局功能 | 全局指令 | v-permission |
复杂交互 | 组合式指令 | v-draggable |
简单样式修改 | 类绑定 | :class=“…” |
通过合理使用自定义指令,可以使代码更简洁、维护性更好,但要注意保持指令的单一职责原则。
评论前必须登录!
注册