vue中自定義指令的使用

原文地址javascript


 

vue中除了內置的指令(v-show,v-model)還容許咱們自定義指令html

想要建立自定義指令,就要註冊指令(以輸入框獲取焦點爲例)vue

1、註冊全局指令:java

// 註冊一個全局自定義指令 `v-focus`
Vue.directive('focus', {
  // 當被綁定的元素插入到 DOM 中時……
  inserted: function (el,binding) {
                // 當前指令綁定的dom元素
                //console.log(el);
                // 指令傳入的參數、修飾符、值  v-指令名稱:參數.修飾符=值
                // console.log(binding)
    // 聚焦元素
    el.focus()
  }
})

  

2、註冊局部指令:node

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

  

使用也很簡單:直接在元素上面使用v-focus便可:git

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

下面再舉一個自定義指令的小例子:拖拽dom

<template>
  <div id="derective">
    <div v-drag class="dragnode">拖拽1</div>
    <div v-drag.limit class="dragnode">拖拽2</div>
  </div>
</template>
<script>
export default {
  name: "derective",
  data() {
    return {};
  },
  directives: {
    // 指令的定義
    drag: {
      bind(el, binding) {
        console.log('bind');
        // 當前指令綁定的dom元素
        console.log(el);
        // 指令傳入的參數、修飾符、值  v-指令名稱:參數.修飾符=值
        console.log(binding)
        el.onmousedown = function(e) {
          var e = e || event;
          let disX = e.clientX - el.offsetLeft;
          let disY = e.clientY - el.offsetTop;

          document.onmousemove = function(e) {
            var e = e || event;
            let L = e.clientX - disX;
            let T = e.clientY - disY;

            if (binding.modifiers.limit) {
              if (L < 0) {
                L = 0;
              }
            }

            el.style.left = L + "px";
            el.style.top = T + "px";
          };

          document.onmouseup = function() {
            document.onmousemove = null;
          };

          return false;
        };
      }
    }
  }
};
</script>
<style scoped>
.dragnode{
  width: 200px;
  height: 200px;
  background-color: #f00;
  position: absolute;
}
</style>

  

使用也很簡單,只用在元素上添加v-drag或者v-drag.limitspa

  1. <div id= "div1" v-drag.limit> </div>
  2. <div id= "div2" v-drag> </div>

 


返回目錄

相關文章
相關標籤/搜索