题目:
根据所学知识,写一个 hooks 函数,来监听键盘上的当前某个按键是否被按下?
const hPress = useKeyPress('h')
<div v-if="hPress">h键被按下啦</div>
任务要求:
1 可以在事件对象 event.key 上面拿到对应的按键名称
2 可以尝试在 keydown 和 keyup 两个 DOM 事件触发对应的修改
参考答案:
import { ref, onMounted, onUnmounted } from 'vue'
const useKeyPress = (targetKeyCode: string) => {
const keyPressed = ref(false)
const keyDownHandler = (e: KeyboardEvent) => {
if(e.key === targetKeyCode) {
keyPressed.value = true
}
}
const keyUpHandler = (e: KeyboardEvent) => {
if(e.key === targetKeyCode) {
keyPressed.value = false
}
}
onMounted(() => {
document.addEventListener('keydown', keyDownHandler)
document.addEventListener('keyup', keyUpHandler)
})
onUnmounted(() => {
document.removeEventListener('keydown', keyDownHandler)
document.removeEventListener('keyup', keyUpHandler)
})
return keyPressed
}
export default useKeyPress