[Vue] Custom Directives 自定義指令

itsems
itsems_frontend
Published in
4 min readMay 24, 2020
Photo by Inside Weather on Unsplash

除了常常用到的 v-model、v-show 之外,如果原生的不夠用,vue 還提供了一種方法可以讓我們直接操作底層的 DOM,就是「自定義指令 Custom Directives」。

Outline:
- 註冊
- 鉤子函數(Hook Functions)
- 鉤子函數參數(Directive Hook Arguments)
- 動態指令參數(Dynamic Directive Arguments)
- 對象字面量(Object Literals)

註冊

註冊分為全域註冊局部註冊,全域註冊如:

/main.js

// 範例為頁面 load 入後自動 focus 自己
Vue.directive('focus', {
inserted: function (el) {
el.focus()
}
})

局部註冊(在 component 內註冊):

/HelloWorld.vue

<script>
methods:{ ... },
directives: {
focus: {
inserted: function (el) {
el.focus()
}
}
}
</script>

註冊完成後在 template 中調用:

/HelloWorld.vue

<template>
<div>
<input v-focus type="text" />
</div>
</template>

就完成一個簡單的頁面 load 進後自動 focus 到自己的 directives 了

鉤子函數 (Hook Functions)

Custom Directives 提供了幾種 hook functions,可以讓我們針對 directive 的生命階段做事情:

簡單看一下 life cycle:

鉤子函數參數 (Directive Hook Arguments)

el

Directives 綁定的元素。

binding

  • name :指令名,不包含 v- 前綴,如 v-demo 的 demo
  • value :傳給 directive 的值,如 v-demo ='hello''hello'
  • oldValue :前一個值,只有在 updatecomponentUpdated 可以調用,不管 value 有沒有變動都可以
  • expression :表達式,如 v-demo = '1+1' 中的 1+1
  • arg :傳給 directive 的參數,如 v-demo:foo 中的 foo
  • modifiers :修飾符,如 v-demo.foo.bar 中的修飾符則為 {foo: true, bar: true}
  • vnode :Vue compiler 生成的虛擬節點,詳見 VNode API
  • oldVnode :前一個虛擬節點,只有在 updatecomponentUpdated 可以調用
除了 el 之外,這些參數都是 read-only,不要更動他們

使用了以上的參數的範例:

可以看到結果:

動態指令參數 (Dynamic Directive Arguments)

這些參數可以式動態的,如 v-demo:[foo]='val' 中的 foo 可以跟著 Vue 實例更新,舉例:

此範例依照 component data 中的 type<p> 會出現藍字或是藍底的兩種 style 狀況。

對象字面量 (Object Literals)

如果想要傳多個值給 directive,也可以傳入物件,directive 接受任何有效的 JavaScript 表達式。

<div v-demo="{ color: 'white', text: 'hello!' }"></div>

Vue Directives 官網文件見此

內容若有任何錯誤,歡迎留言交流指教! 🐬

--

--

itsems
itsems_frontend

Stay Close to Anything that Makes You Glad You are Alive.