项目场景:
antd vue菜单拖动,点击按钮实现展开关闭,拖动菜单右侧实现菜单展开和缩回。
问题描述
拖动菜单后当鼠标释放菜单,菜单依旧跟随鼠标指针移动。
原因分析:
实现拖动需要监听mousemove和mouseup来实现对鼠标的事件的监听,当快速拖动无法对当前事件做节流,导致事件冲突。
解决方案:
<!--
* @Author: jiangyun
* @Date: 2024-01-2 11:21:21
* @Description: html菜单布局
-->
<a-layout-sider
:width="`${lastX}px`"
v-model:collapsed="collapsed"
:trigger="null"
collapsible
style="position: relative"
>
</a-layout-sider>
/**
* @Author: jiangyun
* @Date: 2024-01-2 11:21:21
* @Description: 拖动菜单js逻辑
*/
// 鼠标移动事件,将鼠标指针相对于屏幕的 X 轴坐标赋值给需要动态变化的元素宽度
const mouseMove = (event) => {
if (event.buttons === 1) {
storage.screenX = event.screenX;
lastX.value = event.screenX > 400 ? 400 : event.screenX;
lastX1.value = event.screenX > 400 ? 400 : event.screenX;
newscreenX.size = lastX.value;
// sessionStorage.setItem('screenX',lastX.value)
} else {
mouseUp();
}
};
// 鼠标按下事件
const mouseDown = (event) => {
document.addEventListener("mousemove", mouseMove);
document.addEventListener("mouseup", mouseUp);
// document.onselectstart = function() { return false; };
document.onselectstart = () => false;
// lastX.value = event.screenX;
};
// 鼠标释放事件
const mouseUp = () => {
document.removeEventListener("mousemove", mouseMove);
document.removeEventListener("mouseup", mouseUp);
document.onselectstart = null;
// collapsed.value = false;
// 指定元素可改变的最大以及最小宽度
const moveX =
lastX.value > 400
? 400
: lastX.value < 50
? ((collapsed.value = true), (lastX1.value = 80))
: lastX.value;
lastX.value = moveX;
lastX1.value = moveX;
// document.removeEventListener("mousemove", mouseMove);
};
// 鼠标释放节流事件
const handleMoveThrottled = throttle(mouseUp, 400);
// onMounted时添加鼠标移动事件监听器
onMounted(() => {
// document.addEventListener("mousedown", mouseDown);
document.addEventListener("mouseup", handleMoveThrottled);
});
// 组件卸载时移除监听
onUnmounted(() => {
document.removeEventListener("mouseup", handleMoveThrottled);
});