我正在使用 Pinia 商店系统开发 Vue 应用程序。
我有一个 BoxView.vue 组件,其中包含可拖动元素的网格,并在 BoxItem.vue 中实现了翻转功能。
在 BoxView.vue 中,我有一个附加到“flip-box”元素的“mousedown”事件监听器,它会触发 moveItemInit 函数:
<template>
<div class="boxes-grid">
<div v-for="(box, index) in getAllBoxes" :key="index" class="box-space">
<BoxItem :id="box.id" @mousedown = 'moveItemInit($event.currentTarget as HTMLElement, $event)'> // <--------------------
<template v-slot:front>
<h2>{{ box.frontText }}</h2>
</template>
<template v-slot:back>
<h2>{{ box.backText }}</h2>
</template>
</BoxItem>
</div>
</div>
</template>
在 BoxItem.vue 中,我实现了“rotateInner”函数来通过右键单击翻转元素:
<template>
<div class="flip-box" @contextmenu.prevent="rotateInner" > // <--------------------
<div class="flip-box-inner" :class="{ 'flipped': isFlipped }">
<div class="flip-box-front">
<slot name="front"></slot>
</div>
<div class="flip-box-back">
<slot name="back"></slot>
</div>
</div>
</div>
</template>
<script setup>
...
async function rotateInner(event: MouseEvent) {
if (event.button === 2) {
event.preventDefault()
event.stopPropagation()
isFlipped.value = !isFlipped.value
}
}
</script>
现在,我的问题与以下事实有关:在某个时刻,moveItemInit将一个 EventListener 附加到整个文档,如下所示:
document.onmousemove = (eventNew) => moveItem(flipBoxElement, eventNew);
“moveItem”功能允许通过按住鼠标左键在页面上拖动元素而不受任何限制。我希望能够在拖动元素时通过右键单击它来翻转元素,但是当我这样做时,元素停止移动并返回到其原始位置,在我的情况下,这表明
document.onmouseup = (eventNew) => moveItemEnd(flipBoxElement, eventNew);
过早触发。如何防止右键单击中断 onmousemove 事件,从而使拖动和翻转功能能够无缝工作?任何帮助将不胜感激!
event.preventDefault() 和 event.stopPropagation() 无济于事。
我希望鼠标右键单击不会中断按住鼠标左键并调用“moveItem”函数。
ANY mouseclick 触发了“moveItemEnd”函数:
document.onmouseup = (eventNew) => moveItemEnd(flipBoxElement, eventNew);
为了解决这个问题,我在函数内添加了鼠标按钮检查:
async function moveItemEnd(element: HTMLElement, event: MouseEvent){
if (event.button != 0){
return;
}
...