如何防止点击拖动?

我正在尝试使用拖动和单击事件的元素 . 我已阅读并尝试了event modifiers的组合 .

但是,无论我尝试什么,我都会在拖动停止时点击一下 .

注意,在MWE中,这是在组件本身上完成的,但在我的实际应用程序中,我使用 .native 修饰符来拖动组件

如何在没有点击的情况下拖动?

组件 Draggable

<template>
  <div
    @pointerdown="handleDown"
    @pointerup="handleUp"
    @pointercancel="handleUp"
    @click="click = !click;"
    :style="style"
    ref="draggableRoot"
    class="draggable"
  >
    drag me!
am dragged? {{ drag }}
am clicked? {{ click }}
</div> </template> <script> export default { computed: { style() { return { left: `${this.x}px`, top: `${this.y}px` }; } }, data() { return { x: 100, y: 100, left: 0, top: 0, drag: false, click: false }; }, methods: { handleMove({ pageX, pageY, clientX, clientY }) { if (this.$refs.draggableRoot) { this.x = pageX + this.left; this.y = pageY + this.top; this.drag = true; } }, handleDown(event) { const { pageX, pageY } = event; const { left, top } = this.$refs.draggableRoot.getBoundingClientRect(); this.left = left - pageX; this.top = top - pageY; document.addEventListener("pointermove", this.handleMove); }, handleUp() { document.removeEventListener("pointermove", this.handleMove); this.drag = false; } } }; </script> <style scoped> .draggable { position: fixed; border: solid coral 1px; height: 100px; } </style>

回答(1)

2 years ago

也许这会奏效:

在方法 handleUp 中添加 setTimeout

handleUp() { 
  document.removeEventListener("pointermove", this.handleMove);
  setTimeout(() => this.drag = false) //this would move this assigment at the end of event queue
}

还要添加新方法 handleClick 并将其分配给事件 @click

handleClick() {
  if(!this.drag) { //change click only if not draged
    this.click = !this.click
  }
}

Seems to work!