vue3 实现一个简单的拖拽自定义指令

229 阅读1分钟

实现一个简单的拖拽自定义指令

<template>
  <!-- box 样式 需要给个position的定位,要么移动不起来 -->
  <div v-move class="box">
    <div class="header"></div>
    <div>内容</div>
  </div>
</template>

<script setup lang="ts">
import { Directive, DirectiveBinding } from 'vue'

const vMove:Directive<any,void> = (el:HTMLElement,binding:DirectiveBinding) => {
  let moveElement:HTMLDivElement = el.firstElementChild as HTMLDivElement
  console.log('moveElement:',moveElement)
  const mouseDown = (e:MouseEvent) =>{
    let x = e.clientX - el.offsetLeft
    let y = e.clientY - el.offsetTop
    const move = (e:MouseEvent) =>{
      // 设置边界的最小值
      let curX = e.clientX - x < 0 ? 0 : e.clientX - x
      let curY = e.clientY - y < 0 ? 0 : e.clientY - y
      // 设置边界的最大值 300 为div盒子的宽度 高度
      // curX curY 为 0 时 证明已经到边界最小值,就不需要在判断
      if(curX > 0){
        curX = e.clientX - x > window.innerWidth - 300 ? window.innerWidth - 300 : e.clientX - x
      }
      if(curY > 0){
        curY = e.clientY - y > window.innerHeight - 300 ? window.innerHeight - 300 : e.clientY - y
      }
      el.style.left = curX + 'px'
      el.style.top = curY + 'px'
    }
    // 监听 鼠标移动事件
    document.addEventListener('mousemove',move)
    document.addEventListener('mouseup',()=>{
      document.removeEventListener('mousemove',move)
    })
  }
  // 监听 鼠标按下事件
  moveElement.addEventListener('mousedown',mouseDown)
}

</script>

<style lang="scss" scoped>
.header {
  background: #000;
  height: 50px;
}
.box {
  width:300px;
  height: 300px;
  background: yellow;
  position: absolute;
}
</style>