需要 如果键盘长按上下左右 则执行一定操作
我是封装一个hooks
import { onMounted, onUnmounted } from 'vue';
export const useLongPress = (keyCode: number, callback: any, delay = 100) => {
let timer: any = null;
const startLongPress = (event: any) => {
if (event.keyCode !== keyCode) return;
if (!timer) {
timer = setTimeout(() => {
callback();
timer = null;
}, delay);
}
};
const endLongPress = (event: any) => {
if (event.keyCode !== keyCode) return;
if (timer) {
clearTimeout(timer);
timer = null;
}
};
onMounted(() => {
window.addEventListener('keydown', startLongPress);
window.addEventListener('keyup', endLongPress);
});
onUnmounted(() => {
window.removeEventListener('keydown', startLongPress);
window.removeEventListener('keyup', endLongPress);
});
};
然后再使用的地方
import { useLongPress } from '@/hooks/useLongPress';
// 键盘长按
useLongPress(KeyCode.up, () => {
handleDirection('up');
});