5

我试图让一个元素同时具有拖动和单击事件。我已经阅读并尝试了事件修饰符的组合。

但是,无论我尝试什么,当拖动停止时我都会点击。

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

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

编辑拖动点击

组件Draggable

<template>
  <div
    @pointerdown="handleDown"
    @pointerup="handleUp"
    @pointercancel="handleUp"
    @click="click = !click;"
    :style="style"
    ref="draggableRoot"
    class="draggable"
  >
    drag me!<br />
    am dragged? {{ drag }}<br />
    am clicked? {{ click }}<br />
  </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>
4

1 回答 1

6

也许这会起作用:

添加setTimeout内部方法handleUp

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

还添加新方法handleClick并将其分配给 event @click

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

似乎工作!

于 2018-12-10T21:43:48.090 回答