vu3+ts:mousedown mousemove mouseup 与 click事件冲突的解决办法

2023-12-29 16:22:01
<template>
  <div
    style="position: absolute; width: auto; height: auto; background-color: lightblue; cursor: move"
    :style="{ left: state.positionX + 'px', top: state.positionY + 'px' }"
    @mousedown="handleMouseDown"
  >
    <div class="w-auto h-32 flex items-center" v-for="(item, index) in state.legendTitle" @click="handleEditLegend(item, index)">{{ item.name }}</div>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref } from 'vue'

const state = reactive({
  positionX: 100,
  positionY: 100,
  legendTitle: [{ name: 'hagshagq12hjhsdjk容量0' }, { name: 'hagshagq12hjhsdjk容量1' }, { name: 'hagshagq12hjhsdjk容量2' }],
})

const isDragging = ref(false)
let dragOccurred = false

const handleMouseDown = (event:any) => {
  const startX = event.clientX - state.positionX
  const startY = event.clientY - state.positionY
  dragOccurred = false

  const handleMouseMove = (event:any) => {
    if (!dragOccurred) {
      const deltaX = event.clientX - startX - state.positionX
      const deltaY = event.clientY - startY - state.positionY
      if (Math.abs(deltaX) > 5 || Math.abs(deltaY) > 5) {
        dragOccurred = true
      }
    }

    if (dragOccurred) {
      isDragging.value = true
      state.positionX = event.clientX - startX
      state.positionY = event.clientY - startY
    }
  }

  window.addEventListener('mousemove', handleMouseMove)

  const handleMouseUp = () => {
    window.removeEventListener('mousemove', handleMouseMove)
    window.removeEventListener('mouseup', handleMouseUp)
    isDragging.value = false
  }

  window.addEventListener('mouseup', handleMouseUp)
}

const handleEditLegend = (item:any, index:number) => {
  if (!dragOccurred) {
    console.log(item, '------')
  }
}
</script>

?

文章来源:https://blog.csdn.net/weixin_60886885/article/details/135290718
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。