Vue.directive基础,在Vue模块开发中使用

这是从网上找到的一个案例,由于网上的案例有坑,所以我在这里从新上传一次!

首先在main.js里引入两个自定义指令

import {focus, drag} from './components/darg.js'

  然后创建一个darg.js

import Vue from 'vue'
const focus = Vue.directive('focus', {
  inserted: function(el) {
    el.focus()
    el.setAttribute('placeholder', 'test')
  }
})
const drag = Vue.directive('drag',{
  inserted: function(el) { //inserted 钩子函数:当元素被插入父元素时触发,可省略
    let oDiv = el; //el --> 触发的DOM元素
   oDiv.style.position='relative';
    oDiv.onmousedown = function(e) {
      let l = e.clientX - oDiv.offsetLeft;
      let t = e.clientY - oDiv.offsetTop;
      document.onmousemove = function(e) {
        oDiv.style.left = e.clientX - l + 'px';
        oDiv.style.top = e.clientY - t + 'px';
      };
      oDiv.onmouseup = function() {
        document.onmousemove = null;
        oDiv.onmouseup = null;
      }
    }
  }
  })

export { focus, drag}

  这里面有两个自定义指令一个是自动input自动对焦,一个是div的拖拽,红色是我遇到的坑,网上代码没有{}所以我这里标出来。

最后随意创建一个.vue的文件,这里我就创建一个Hello.vue

<template>
  <div>
        <div class="ddd" v-drag>我可以拖拽</div>
        <input type="text" v-focus />
  </div>
</template>
<script>
</script>
<style>
</style>

  最后纠正下,其实顺序是先写darg.js,再引入到main.js之后就可以再Hello.vue里使用自定义指令了。、

希望对大家有帮助,谢谢