Vue3自定義指令完全指南(附詳細代碼)
更新時間:2025年04月27日 09:00:23 作者:john_Asura
這篇文章主要介紹了Vue3自定義指令的相關資料,Vue3自定義指令優(yōu)化了生命周期鉤子,提供了更靈活的DOM操作方式,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
基本概念
在Vue3中,自定義指令是用于直接操作DOM的重要工具。相比Vue2,Vue3的指令系統(tǒng)進行了優(yōu)化和簡化。
生命周期鉤子
| 鉤子名稱 | 對應Vue2名稱 | 觸發(fā)時機 |
|---|---|---|
| created | bind | 元素屬性綁定前 |
| beforeMount | inserted | 元素插入父節(jié)點前 |
| mounted | - | 元素插入父節(jié)點后 |
| 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>
// 實現(xiàn)
app.directive('focus', {
mounted(el) {
el.focus()
}
})
2. 權限控制
// 使用
<button v-permission="['admin']">刪除</button>
// 實現(xiàn)
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>
// 實現(xiàn)
app.directive('debounce', {
mounted(el, binding) {
let timer = null
el.addEventListener(binding.arg, () => {
clearTimeout(timer)
timer = setTimeout(() => {
binding.value()
}, 500)
})
}
})
進階技巧
動態(tài)參數(shù)傳遞
// 使用
<div v-pin:[direction]="200"></div>
// 實現(xiàn)
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()
}
})
注意事項
- 避免過度使用:優(yōu)先使用組件化方案
- 參數(shù)驗證:使用
binding.value前進行類型檢查 - 性能優(yōu)化:及時在unmounted階段清理副作用
- 命名規(guī)范:使用小寫字母+連字符格式(如
v-custom-directive) - 瀏覽器兼容:謹慎使用新API,必要時添加polyfill
總結
| 場景 | 推薦指令類型 | 示例 |
|---|---|---|
| DOM操作 | 自定義指令 | v-tooltip |
| 全局功能 | 全局指令 | v-permission |
| 復雜交互 | 組合式指令 | v-draggable |
| 簡單樣式修改 | 類綁定 | :class=“…” |
通過合理使用自定義指令,可以使代碼更簡潔、維護性更好,但要注意保持指令的單一職責原則。
到此這篇關于Vue3自定義指令的文章就介紹到這了,更多相關Vue3自定義指令內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue3 微信掃碼登錄及獲取個人信息實現(xiàn)的三種方法
本文主要介紹了vue3 微信掃碼登錄及獲取個人信息實現(xiàn)的三種方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-03-03
Vue2.0利用 v-model 實現(xiàn)組件props雙向綁定的優(yōu)美解決方案
本篇文章主要介紹了Vue2 利用 v-model 實現(xiàn)組件props雙向綁定的優(yōu)美解決方案,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-03-03
vue3項目+element-plus:時間選擇器格式化方式
這篇文章主要介紹了vue3項目+element-plus:時間選擇器格式化方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03

