vue 自定義指令及動態指令參數


場景
1.為組件添加loading效果
2.按鈕級別權限控制 v-permission
3.代碼埋點,根據操作類型定義指令
4.input 輸入框自動獲取焦點

注意事項
注意:
    1.自定義指令名稱,不能使用駝峰規則,而應該使用"my-dir" 或 “my_dir” 或 “mydir”
    2.使用時,必須加v-    如:<p v-my-dir="xxxx"></p>

指令的生命周期
1.bind
 只調用一次,指令第一次綁定到元素時調用,用這個鈎子函數可以定義一個在綁定時執行一次的初始化動作。

2.inserted
 被綁定元素插入父節點時調用(父節點存在即可調用,不必存在於 document 中)。

3update
 所在組件的 VNode 更新時調用,但是可能發生在其孩子的 VNode 更新之前。指令的值可能發生了改變也可能沒有。但是可以通過比較更新前后的值來忽略不必要的模板更新。

3.componentUpdated
 所在組件的 VNode 及其孩子的 VNode 全部更新時調用。

4.unbind
    只調用一次, 指令與元素解綁時調用。

鈎子函數的參數
1.el 
    指令所綁定的元素,可以用來直接操作 DOM。
2.binding一個對象,包含以下屬性:
    name: 指令名,不包括 v- 前綴。
    value: 指令的綁定值, 例如: v-my-directive="1 + 1", value 的值是 2。
    oldValue: 指令綁定的前一個值,僅在 update 和 componentUpdated 鈎子中可用。無論值是否改變都可用。
    expression: 綁定值的字符串形式。 例如 v-my-directive="1 + 1" , expression 的值是 "1 + 1"。
    arg: 傳給指令的參數。例如 v-my-directive:foo, arg 的值是 "foo"。
    modifiers: 一個包含修飾符的對象。 例如: v-my-directive.foo.bar, 修飾符對象 modifiers 的值是 { foo: true, bar: true }。

3.vnode 
    編譯生成的虛擬節點。
4.oldVnode】
    上一個虛擬節點,僅在 update 和 componentUpdated 鈎子中可用。

示例: 
    bind: function (el, binding, vnode) {}
  
[注意]除了 el 之外,其它參數都是只讀的,盡量不要修改他們。如果需要在鈎子之間共享數據,建議通過元素的 dataset 來進行。

聲明局部指令
<template>
  <div class="hello">
      <div v-test='name'></div>
  </div>
</template>
<script>
export default {
  data () {
    return {
     name:'我是名字',
    }
  },
  directives:{
      test:{
        inserted: function (el,binding) {// 指令的定義
           el.style.position = 'fixed'
               el.style.top = binding.value + 'px'
        },
        bind: function (el, binding, vnode) {

            }
      }
  }
}

全局聲明指令
main.js
示例:
    import Vue from 'vue';
    Vue.directive('focus',{
       bind:function(e,v){
           console.log('bind指令')
       },
       inserted:function(e,v){
           console.log('inserted指令')
           console.log(this)        //  指令內部this指向window
           e.focus();
       },
       update:function(){
           console.log('update指令')
       }
    })


動態指令參數
指令的傳參類型有兩種:
    1. v-xxxx="參數"
        通過binding.value接收
    2. v-xxx:參數1="參數2"   
        通過binding.arg
場景:我們需要把元素需要動態的固定在左或者頂部?

使用:
<div v-for="(item, index) in list" :key="index">
    <div v-zoom:{direction:item.direcition}="{width: item.width, height: item,height}"></div>
</div>
<script>
    data () {
        return {
            list: [
                {width: 100, height: 200, direction: 'left'},
                {width: 140, height: 240, direction: 'top'}
            ]
        }
    }
</script>

聲明指令
directive('pin', {
    bind: function (el, binding, vnode) {
        el.style.position = 'fixed'
        var s = (binding.arg.direction == 'left' ? 'left' : 'top')
        el.style[s] = binding.value + 'px'
    }
})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM