vue自定义拖动指令

1、在项目开发中,需要对div进行拖动。因为需要自定义组件

a》定义全局拖拽指令:

  定义全局指令,需要在main.js中写入vue.directive('drag',{});即可。但是一般会在外部新建一个drag.js文件,在js文件内部实现拖拽逻辑,最后在dom代码中调用该指令:

  (1)、新建drag.js文件:

import Vue from 'vue';
//使用Vue.directive()定义一个全局指令
//1.参数一:指令的名称,定义时指令前面不需要写v-
//2.参数二:是一个对象,该对象中有相关的操作函数
//3.在调用的时候必须写v-
const drag = Vue.directive('drag',{
  //1.指令绑定到元素上回立刻执行bind函数,只执行一次
  //2.每个函数中第一个参数永远是el,表示绑定指令的元素,el参数是原生js对象
  //3.通过el.focus()是无法获取焦点的,因为只有插入DOM后才生效
  bind:function(el){},
  //inserted表示一个元素,插入到DOM中会执行inserted函数,只触发一次
  inserted:function(el){
    el.onmousedown = function (e) {
      var disx = e.pageX - el.offsetLeft;
      var disy = e.pageY - el.offsetTop;
      document.onmousemove = function (e) {
        el.style.left = e.pageX - disx + 'px';
        el.style.top = e.pageY - disy + 'px';
      }
      document.onmouseup = function () {
        document.onmousemove = document.onmouseup = null;
      }
    }
  },
  //当VNode更新的时候会执行updated,可以触发多次
  updated:function(el) {}
})
export default drag;

  ===========以下是:更新于2021年6月2号。由于鼠标拖动事件,不大好用,因此修改了一下拖拽指令===========  

  使用了鼠标点击事件,onClick

import Vue from "vue";
// 使用Vue.directive()定义一个全局指令
// 1.参数一:指令的名称,定义时指令前面不需要写v-
// 2.参数二:是一个对象,该对象中有相关的操作函数
// 3.在调用的时候必须写v-
const drag = Vue.directive("drag", {
  // 1.指令绑定到元素上回立刻执行bind函数,只执行一次
  // 2.每个函数中第一个参数永远是el,表示绑定指令的元素,el参数是原生js对象
  // 3.通过el.focus()是无法获取焦点的,因为只有插入DOM后才生效
  bind: () => {},
  // inserted表示一个元素,插入到DOM中会执行inserted函数,只触发一次
  inserted: (el) => {
    let isDrag = false;
    el.onclick = function (e) {
      isDrag = !isDrag;
      if (isDrag) {
        const disx = e.pageX - el.offsetLeft;
        const disy = e.pageY - el.offsetTop;
        document.onmousemove = function (e) {
          el.style.left = `${e.pageX - disx}px`;
          el.style.top = `${e.pageY - disy}px`;
        };
        document.onmouseup = function () {
          document.onmousemove = null;
          document.onmouseup = null;
        };
      }
    };
  },
  // 当VNode更新的时候会执行updated,可以触发多次
  updated: () => {},
});
export default drag;

  

  (2)、在main.js中引入该文件即可。不需要vue.use();

  

  (3)、在页面中直接调用

 

b》定义局部拖拽指令:

  局部指令,只需要要对应的.vue页面中,添加directives属性,并在directives中写入对应的指令即可。

 

posted on 2019-04-10 14:59  紫藤萝yu  阅读(5573)  评论(0)    收藏  举报