我试图让一个元素同时具有拖动和单击事件。我已经阅读并尝试了事件修饰符的组合。
但是,无论我尝试什么,当拖动停止时我都会点击。
请注意,在 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>