Vue自定義指令以及自定義指令的模組化

2021-10-13 00:25:10 字數 2095 閱讀 2006

如果vue內建的指令不能滿足功能需求的時候,可以進行自定義指令。

自定義指令的使用場景就是操作基礎dom,實現功能需求。

官方文件

自定義指令的五個鉤子函式都是可選的,比如 v-once 指令。

bind

指令第一次繫結到元素上;只呼叫一次;可以做相關初始化的操作;

inserted

被繫結的元素插入到其父元素節點時呼叫;

update

當所在元件的vnode更新時呼叫;但是update和vnode的更新順序不定,所以需要比較;

componentupdated

指令所在元件的vnode及其子vnode全部更新完成後呼叫;

unbind

解綁;只呼叫一次

和元件一樣,自定義指令也分全域性指令和區域性指令。

全域性指令:

vue.

directive

('my-directive',,

// 被繫結元素插入父節點時呼叫

inserted

(el, binding, vnode)

,// 所在元件的 vnode 更新時呼叫

update

(el, binding, vnode)

,// 指令所在元件的 vnode 及其子 vnode 全部更新後呼叫

componentupdated

(el, binding, vnode)

,unbind

(el, binding, vnode)})

;

區域性指令:

@component(,

directives:

,// 被繫結元素插入父節點時呼叫

inserted

(el, binding, vnode)

,// 所在元件的 vnode 更新時呼叫

update

(el, binding, vnode)

,// 指令所在元件的 vnode 及其子 vnode 全部更新後呼叫

componentupdated

(el, binding, vnode)

,unbind

(el, binding, vnode),}

,},}

)

// module-directive.js

export

default

,// 被繫結元素插入父節點時呼叫

inserted

(el, binding, vnode)

,// 所在元件的 vnode 更新時呼叫

update

(el, binding, vnode)

,// 指令所在元件的 vnode 及其子 vnode 全部更新後呼叫

componentupdated

(el, binding, vnode)

,unbind

(el, binding, vnode)

}

建立好模組化的指令後,通過index.js管理指令:

import mydirective from

'./modules/mydirective'

export

統一管理模組化指令後,在main.js中進行全域性註冊:

import

*as directives from

'./directives'

object.

keys

(directives)

.foreach

(index => vue.

directive

(index, directives[index]

))

全域性註冊後,即可通過 v-directive_name使用。

需要注意的是,在翻其他博主的文章時,有提到自定義指令不能在資料更新的時候同步響應。

這個問題是和自定義指令的鉤子函式有關,具體情況需要根據自己指令的需求去調整。

Vue自定義指令

vue有很多內建的指令,比如說v on,v model,v clock等等,每乙個指令會完成一定的功能,但是這些內建的指令總會有些侷限性,要是能夠自定義指令就好了 vue的自定義指令分類 全域性指令和區域性指令 vue指令的定義和用法 以全域性指令為例 1.語法 vue.directive 指令id...

vue自定義指令

自定義指令主要有兩種方式。一是在元件裡以directives的選項來自定義指令的內容。這樣的自定義指令是區域性的自定義指令,只在當前的元件裡面才能使用。script export default directives arr arr.join el.style.csstext arr script ...

VUE 自定義指令

dom插入便獲取焦點 vue.directive focus 根據指令的值決定自否獲取焦點 vue.directive focus 注 被拖拽的元素必須有定位樣式 vue.directive drag function el,binding document.nm useup function 拓展...