vue3自定义拖拽指令

<template>
  <div v-move class="box">
    
  </div>
</template>

<script setup lang="ts"> 
import { Directive } from 'vue'
const vMove:Directive = (el:HTMLElement) =>{
  const mousedown = (e:MouseEvent) =>{
    // 鼠标按下
    const startX = e.clientX - el.offsetLeft;
    const startY = e.clientY  - el.offsetHeight;
    const move = (e:MouseEvent)=> {
      console.log('坐标',e.clientX, e.clientY);
      // 鼠标移动
      const moveX = e.clientX;
      const moveY = e.clientY;
      const disX = moveX - startX;
      const disY = moveY - startY;
      el.style.top = disY + 'px'
      el.style.left = disX + 'px'
    }
    const up = () => {
      // 鼠标抬起
      document.removeEventListener('mousemove',move)
      document.removeEventListener('mouseup',up)
    } 
    document.addEventListener('mousemove',move)
    document.addEventListener('mouseup',up)
  }
  el.addEventListener('mousedown',mousedown)
} 
</script>

<style scoped>
.box {
  width: 400px;
  height: 400px;
  background: pink;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>

vue3自定义拖拽指令_第1张图片
vue3自定义拖拽指令_第2张图片

你可能感兴趣的:(vue,面试,javascript,开发语言,ecmascript)