天天看點

Vue學習記錄--自定義指令讓文本框獲得焦點,為綁定的元素設定指定的字型顔色 和 字型粗細

​​自定義指令​​

  1. 自定義全局和局部的 自定義指令:
// 自定義全局指令 v-focus,為綁定的元素自動擷取焦點:

    Vue.directive('focus', {

      inserted: function (el) { // inserted 表示被綁定元素插入父節點時調用

        el.focus();

      }

    });



    // 自定義局部指令 v-color 和 v-font-weight,為綁定的元素設定指定的字型顔色 和 字型粗細:

      directives: {

        color: { // 為元素設定指定的字型顔色

          bind(el, binding) {

            el.style.color = binding.value;

          }

        },

        'font-weight': function (el, binding2) { // 自定義指令的簡寫形式,等同于定義了 bind 和 update 兩個鈎子函數

          el.style.fontWeight = binding2.value;

        }

      }      
  1. 自定義指令的使用方式:
<input type="text" v-model="searchName" v-focus v-color="'red'" v-font-weight="900">      

Vue 1.x 中 自定義元素指令【已廢棄,了解即可】

Vue.elementDirective('red-color', {
  bind: function () {
    this.el.style.color = 'red';
  }
});      
<red-color>1232</red-color>      

自定義全局指令

// 使用  Vue.directive() 定義全局的指令  v-focus
    // 其中:參數1 : 指令的名稱,注意,在定義的時候,指令的名稱前面,不需要加 v- 字首, 
    // 但是: 在調用的時候,必須 在指令名稱前 加上 v- 字首來進行調用
    //  參數2: 是一個對象,這個對象身上,有一些指令相關的函數,這些函數可以在特定的階段,執行相關的操作
    Vue.directive('focus', {
      bind: function (el) { // 每當指令綁定到元素上的時候,會立即執行這個 bind 函數,隻執行一次
        // 注意: 在每個 函數中,第一個參數,永遠是 el ,表示 被綁定了指令的那個元素,這個 el 參數,是一個原生的JS對象
        // 在元素 剛綁定了指令的時候,還沒有 插入到 DOM中去,這時候,調用 focus 方法沒有作用
        //  因為,一個元素,隻有插入DOM之後,才能擷取焦點
        // el.focus()
      },
      inserted: function (el) {  // inserted 表示元素 插入到DOM中的時候,會執行 inserted 函數【觸發1次】
        el.focus()
        // 和JS行為有關的操作,最好在 inserted 中去執行,放置 JS行為不生效
      },
      updated: function (el) {  // 當VNode更新的時候,會執行 updated, 可能會觸發多次

      }
    })



    // 自定義一個 設定字型顔色的 指令
    Vue.directive('color', {
      // 樣式,隻要通過指令綁定給了元素,不管這個元素有沒有被插入到頁面中去,這個元素肯定有了一個内聯的樣式
      // 将來元素肯定會顯示到頁面中,這時候,浏覽器的渲染引擎必然會解析樣式,應用給這個元素
      bind: function (el, binding) {
        // el.style.color = 'red'
        // console.log(binding.name)
        // 和樣式相關的操作,一般都可以在 bind 執行

        // console.log(binding.value)
        // console.log(binding.expression)

        el.style.color = binding.value
      }
    })      

自定義私有指令

directives: { // 自定義私有指令
        'fontweight': { // 設定字型粗細的
          bind: function (el, binding) {
            el.style.fontWeight = binding.value
          }
        },
        'fontsize': function (el, binding) { // 注意:這個 function 等同于 把 代碼寫到了 bind 和 update 中去
          el.style.fontSize = parseInt(binding.value) + 'px'
        }
      }