云计算百科
云计算领域专业知识百科平台

Vue3 自定义指令完全指南

Vue3 自定义指令完全指南

目录

  • 基本概念
  • 指令注册方式
  • 常用应用场景
  • 注意事项

基本概念

在Vue3中,自定义指令是用于直接操作DOM的重要工具。相比Vue2,Vue3的指令系统进行了优化和简化。

生命周期钩子

钩子名称对应Vue2名称触发时机
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 vfocus>

// 实现
app.directive('focus', {
mounted(el) {
el.focus()
}
})

2. 权限控制

// 使用
<button vpermission="['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 vdebounce:click="submitForm">提交</button>

// 实现
app.directive('debounce', {
mounted(el, binding) {
let timer = null
el.addEventListener(binding.arg, () => {
clearTimeout(timer)
timer = setTimeout(() => {
binding.value()
}, 500)
})
}
})


进阶技巧

动态参数传递

// 使用
<div vpin:[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()
}
})


注意事项

  • 避免过度使用:优先使用组件化方案
  • 参数验证:使用binding.value前进行类型检查
  • 性能优化:及时在unmounted阶段清理副作用
  • 命名规范:使用小写字母+连字符格式(如v-custom-directive)
  • 浏览器兼容:谨慎使用新API,必要时添加polyfill

  • 总结

    场景推荐指令类型示例
    DOM操作 自定义指令 v-tooltip
    全局功能 全局指令 v-permission
    复杂交互 组合式指令 v-draggable
    简单样式修改 类绑定 :class=“…”

    通过合理使用自定义指令,可以使代码更简洁、维护性更好,但要注意保持指令的单一职责原则。

    赞(0)
    未经允许不得转载:网硕互联帮助中心 » Vue3 自定义指令完全指南
    分享到: 更多 (0)

    评论 抢沙发

    评论前必须登录!