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

这是从网上找到的一个案例,因为网上的案例有坑,因此我在这里重新上传一次!javascript

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

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

  而后建立一个darg.jsjava

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 spa

<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里使用自定义指令了。、component

但愿对你们有帮助,谢谢blog

相关文章
相关标签/搜索