1. 程式人生 > 其它 >Vue自定義指令的概念及使用。

Vue自定義指令的概念及使用。

技術標籤:vue

Vue自定義指令:directive

在Vue中,除了預設設定的核心指令(v-modelv-show),Vue也允許自定義指令directive.

自定義指令分為全域性自定義指令區域性自定義指令

全域性自定義指令:

使用Vue.directive來全域性註冊指令。

Vue.directive('focus', {
 		// 當繫結元素插入到 DOM 中。
		inserted: function (el) {
  		// 聚焦元素
 		 el.focus()
	   }
	})

區域性自定義指令:

在元件或者Vue建構函式中接收一個directives的選項,來註冊區域性指令。

 directives: {
 		 // 註冊一個區域性的自定義指令 v-focus
		focus: {
  			// 指令的定義
     		inserted: function (el) {
        	// 聚焦元素
       		 el.focus()
    		}
		 }
	  }

自定義指令的鉤子函式

指令定義函式提供了幾個鉤子函式:

  • bind繫結元素的時候呼叫
  • inserted:繫結的元素插入父節點時呼叫
  • Updata:繫結元素的值改變之前呼叫
  • componentupdata:繫結的元素改變之後呼叫
  • unbind: 解綁元素的時候呼叫

鉤子函式函式

  • el:繫結的元素,用來操作DOM
  • binding:繫結的物件資訊,包含以下屬性。
    • name : 指令的名字
    • value : 指令的值
    • oldValue: 指令繫結的前一個值,僅在updatecomponentUpdated鉤子中可用。無論值是否改變都可用。
    • 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 }。
  • vnode: Vue 編譯生成的虛擬節點,查閱 VNode API 瞭解更多詳情。
  • oldVnode: 上一個虛擬節點,僅在 update 和 componentUpdated 鉤子中可用。

使用Vue自定義指令封裝一個拖拽的盒子

Vue.directive("drag", {                     //指令的名稱
    inserted: function (el, binding) {      //當被繫結的元素插入到 DOM 中時
        el.style.position = "absolute";
        el.style.left = binding.arg.left + "px";
        el.style.top = binding.arg.top + "px";
        el.onmousedown = function (e) {
            var x = e.offsetX;
            var y = e.offsetY;
            document.onmousemove = function (eve) {
                el.style.left = eve.clientX - x + "px";
                el.style.top = eve.clientY - y + "px";
            }
            document.onmouseup = function () {
                document.onmousemove = null;
                document.onmouseup = null;
            }
        }
}