Vue2.x和3.x自定义拖拽指令

250 阅读1分钟

Vue自定义拖拽指令

2.x定义指令

//自定义drag指令
Vue.directive('drag', {
	bind:function (el, binding) {
        let oDiv = el;   //当前元素
        let self = this;  //上下文
        oDiv.onmousedown = function (e) {
            //鼠标按下,计算当前元素距离可视区的距离
            let disX = e.clientX - oDiv.offsetLeft;
            let disY = e.clientY - oDiv.offsetTop;
            document.onmousemove = function (e) {
                //通过事件委托,计算移动的距离 
                let l = e.clientX - disX;
                let t = e.clientY - disY;
                //移动当前元素  
                oDiv.style.left = l + 'px';
                oDiv.style.top = t + 'px';
                //将此时的位置传出去
                binding.value({x:e.pageX,y:e.pageY}, el)
            };
            document.onmouseup = function (e) {
                document.onmousemove = null;
                document.onmouseup = null;
            };
        };
	}
})

3.x自定义指令

import { createApp } from 'vue'
import App from './App.vue'
let app = createApp(App)

app.directive('drag', {
  beforeMount (el, binding) {
    console.log(el, binding)
    let oDiv = el;   //当前元素
    oDiv.onmousedown = function (e) {
     //鼠标按下,计算当前元素距离可视区的距离
      let disX = e.clientX - oDiv.offsetLeft;
      let disY = e.clientY - oDiv.offsetTop;
      document.onmousemove = function (e) {
        //通过事件委托,计算移动的距离 
        let l = e.clientX - disX;
        let t = e.clientY - disY;
        //移动当前元素  
        oDiv.style.left = l + 'px';
        oDiv.style.top = t + 'px';
         //将此时的位置传出去
        binding.value({x:e.pageX,y:e.pageY}, el)
      };
      document.onmouseup = function () {
        document.onmousemove = null;
        document.onmouseup = null;
      };
    };
  }
})

使用指令

<!-- 绑定 -->
<div v-drag="greet" class="closeBut">
    使用拖拽自定义指令
</div>
//使用函数
greet(val, el) {			
	// 返回的val和el元素
}