vue中自定义指令的使用

原文地址


vue中除了内置的指令(v-show,v-model)还允许我们自定义指令

想要创建自定义指令,就要注册指令(以输入框获取焦点为例)

一、注册全局指令:

// 注册一个全局自定义指令 `v-focus`
Vue.directive('focus', {
  // 当被绑定的元素插入到 DOM 中时……
  inserted: function (el,binding) {
                // 当前指令绑定的dom元素
                //console.log(el);
                // 指令传入的参数、修饰符、值  v-指令名称:参数.修饰符=值
                // console.log(binding)
    // 聚焦元素
    el.focus()
  }
})

  

二、注册局部指令:

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

  

使用也很简单:直接在元素上面使用v-focus即可:

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

下面再举一个自定义指令的小例子:拖拽

<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{
   200px;
  height: 200px;
  background-color: #f00;
  position: absolute;
}
</style>

  

使用也很简单,只用在元素上添加v-drag或者v-drag.limit

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

返回目录

原文地址:https://www.cnblogs.com/gitByLegend/p/10871914.html