VueUse onKeyStroke 监听按键,比如你监听了a键,当用户按下a键时你将会接收到该事件。
import { onKeyStroke } from '@vueuse/core'
onKeyStroke('a', (e) => {
//按下了a键
e.preventDefault()
})
//同时监听多个键
onKeyStroke(['s', 'S', 'ArrowDown'], (e) => {
console.log('你按下了:'+e.key)
e.preventDefault()
})
// 监听所有标准键,不包含特殊的键
// 比如韩语键盘定义了其他键或不包含数字键
onKeyStroke(true, (e) => {
console.log('你按下了:'+e.key)
e.preventDefault()
})
// 监听所有标准键
onKeyStroke((e) => {
e.preventDefault()
})
onKeyStroke('A', (e) => {
console.log('在document元素里按下了a键')
}, { target: document })
import { onKeyStroke } from '@vueuse/core'
// use `autoRepeat` option
onKeyStroke('A', (e) => {
console.log('Key A pressed')
}, { dedupe: true })
<script setup lang="ts">
import { vOnKeyStroke } from '@vueuse/components'
//响应的事件
function onUpdate(e: KeyboardEvent) {
console.log('你按下了:'+e.key)
}
</script>
<template>
<input v-on-key-stroke:c,v="onUpdate" type="text">
<!-- with options -->
<input v-on-key-stroke:c,v="[onUpdate, { eventName: 'keyup' }]" type="text">
</template>
//当然按键松开才会响应
onKeyStroke('Shift', (e) => {
console.log('Shift key up')
}, { eventName: 'keyup' })
//或者
onKeyUp('Shift', () => console.log('Shift key up'))
例子
export type KeyPredicate = (event: KeyboardEvent) => boolean
export type KeyFilter = true | string | string[] | KeyPredicate
export type KeyStrokeEventName = "keydown" | "keypress" | "keyup"
export interface OnKeyStrokeOptions {
eventName?: KeyStrokeEventName
target?: MaybeRefOrGetter<EventTarget | null | undefined>
passive?: boolean
/**
* Set to `true` to ignore repeated events when the key is being held down.
*
* @default false
*/
dedupe?: MaybeRefOrGetter<boolean>
}
/**
* Listen for keyboard keystrokes.
*
* @see https://vueuse.org/onKeyStroke
*/
export declare function onKeyStroke(
key: KeyFilter,
handler: (event: KeyboardEvent) => void,
options?: OnKeyStrokeOptions,
): () => void
export declare function onKeyStroke(
handler: (event: KeyboardEvent) => void,
options?: OnKeyStrokeOptions,
): () => void
/**
* Listen to the keydown event of the given key.
*
* @see https://vueuse.org/onKeyStroke
* @param key
* @param handler
* @param options
*/
export declare function onKeyDown(
key: KeyFilter,
handler: (event: KeyboardEvent) => void,
options?: Omit<OnKeyStrokeOptions, "eventName">,
): () => void
/**
* Listen to the keypress event of the given key.
*
* @see https://vueuse.org/onKeyStroke
* @param key
* @param handler
* @param options
*/
export declare function onKeyPressed(
key: KeyFilter,
handler: (event: KeyboardEvent) => void,
options?: Omit<OnKeyStrokeOptions, "eventName">,
): () => void
/**
* Listen to the keyup event of the given key.
*
* @see https://vueuse.org/onKeyStroke
* @param key
* @param handler
* @param options
*/
export declare function onKeyUp(
key: KeyFilter,
handler: (event: KeyboardEvent) => void,
options?: Omit<OnKeyStrokeOptions, "eventName">,
): () => void