天天看點

自定義指令directives

directives

  • 類型:​

    ​Object​

  • 詳細:

    聲明一組可用于元件執行個體中的指令。

  • 用法:
const app = createApp({})

app.component('focused-input', {
  directives: {
    focus: {
      mounted(el) {
        el.focus()
      }
    }
  },
  template: `<input v-focus>`
})      

簡介

除了核心功能預設内置的指令 (例如 ​

​v-model​

​​ 和 ​

​v-show​

​),Vue 也允許注冊自定義指令。

注意,在 Vue 中,代碼複用和抽象的主要形式是元件。然而,有的情況下,你仍然需要對普通 DOM 元素進行底層操作,這時候就會用到自定義指令。

例:

當頁面加載時,輸入框将獲得焦點 (注意:​

​autofocus​

​ 在移動版 Safari 上不工作)。

事實上,如果你在打開這個頁面後還沒有點選過任何内容,那麼此時這個輸入框就應當處于聚焦狀态。

const app = Vue.createApp({})
// 注冊一個全局自定義指令 `v-focus`
app.directive('focus', {
  // 當被綁定的元素挂載到 DOM 中時……
  mounted(el) {
    // 聚焦元素
    el.focus()
  }
})      

如果想注冊局部指令,元件中也接受一個 ​

​directives​

​ 的選項:

directives: {
  focus: {
    // 指令的定義
    mounted(el) {
      el.focus()
    }
  }
}

//然後你可以在模闆中任何元素上使用新的 v-focus attribute,如下:

<input v-focus />      

鈎子函數

一個指令定義對象可以提供如下幾個鈎子函數 (均為可選):

  • ​created​

    ​​:在綁定元素的 attribute 或事件監聽器被應用之前調用。在指令需要附加在普通的 ​

    ​v-on​

    ​ 事件監聽器調用前的事件監聽器中時,這很有用。
  • ​beforeMount​

    ​:當指令第一次綁定到元素并且在挂載父元件之前調用。
  • ​mounted​

    ​:在綁定元素的父元件被挂載前調用。
  • ​beforeUpdate​

    ​:在更新包含元件的 VNode 之前調用。
  • ​updated​

    ​:在包含元件的 VNode 及其子元件的 VNode 更新後調用。
  • ​beforeUnmount​

    ​:在解除安裝綁定元素的父元件之前調用
  • ​unmounted​

    ​:當指令與元素解除綁定且父元件已解除安裝時,隻調用一次。

還可以加動态的一個參數,比如一開始我要某個元素 高 = 500,那麼就在el 後面加個參數叫binding,然後取值是 binding.value ,例:

指令的參數可以是動态的。例如,在 ​

​v-mydirective:[argument]="value"​

​​ 中,​

​argument​

​ 參數可以根據元件執行個體資料進行更新!這使得自定義指令可以在應用中被靈活使用。

例如你想要建立一個自定義指令,用來通過固定布局将元素固定在頁面上。我們可以建立一個自定義指令,它的值以像素為機關更新被固定元素的垂直位置,如下所示:

<div id="dynamic-arguments-example" class="demo">
  <p v-pin="200">Stick me 200px from the top of the page</p>
</div>      
const app = Vue.createApp({})

app.directive('pin', {
  mounted(el, binding) {
    el.style.position = 'fixed'
    // binding.value 是我們傳遞給指令的值——在這裡是 200
    el.style.top = binding.value + 'px'
  }
})

app.mount('#dynamic-arguments-example')      

這會把該元素固定在距離頁面頂部 200 像素的位置。但如果場景是我們需要把元素固定在左側而不是頂部又該怎麼辦呢?這時使用動态參數就可以非常友善地根據每個元件執行個體來進行更新。

<div id="dynamicexample">
  <h3>Scroll down inside this section ↓</h3>
  <p v-pin:[direction]="200">I am pinned onto the page at 200px to the left.</p>
</div>      
const app = Vue.createApp({
  data() {
    return {
      direction: 'right'
    }
  }
})

app.directive('pin', {
  mounted(el, binding) {
    el.style.position = 'fixed'
    // binding.arg 是我們傳遞給指令的參數
    const s = binding.arg || 'top'
    el.style[s] = binding.value + 'px'
  }
})

app.mount('#dynamic-arguments-example')      

基本用法就這些,更多簡寫什麼的看文檔即可:

​​https://v3.cn.vuejs.org/guide/custom-directive.html​​

上一篇: 2013年4月1日
下一篇: 2013年8月18日