Skip to content

useMagicKeys

类别
导出体积
1.17 kB
上次更改
6 minutes ago

响应式按键按下状态,支持神奇按键组合。

示例

按以下键测试
V
u
e
U
s
e
Shift
Vue
Use
已按下的键

使用方法

ts
import { 
useMagicKeys
} from '@vueuse/core'
const {
shift
,
space
,
a
/* keys you want to monitor */ } =
useMagicKeys
()
watch
(
space
, (
v
) => {
if (
v
)
console
.
log
('空格键被按下')
})
watchEffect
(() => {
if (
shift
.
value
&&
a
.
value
)
console
.
log
('Shift + A 已经被按下')
})

检查所有可能的按键码

组合键

你可以通过使用 +_ 将键连接起来,以使用组合键 (快捷键/热键)。

ts
import { 
useMagicKeys
} from '@vueuse/core'
const
keys
=
useMagicKeys
()
const
shiftCtrlA
=
keys
['Shift+Ctrl+A']
watch
(
shiftCtrlA
, (
v
) => {
if (
v
)
console
.
log
('Shift + Ctrl + A 已经被按下')
})
ts
import { 
useMagicKeys
} from '@vueuse/core'
const {
Ctrl_A_B
,
space
,
alt_s
/* ... */ } =
useMagicKeys
()
watch
(
Ctrl_A_B
, (
v
) => {
if (
v
)
console
.
log
('Control+A+B 已经被按下')
})

你还可以使用 whenever 函数来使代码更简洁

ts
import { 
useMagicKeys
,
whenever
} from '@vueuse/core'
const
keys
=
useMagicKeys
()
whenever
(
keys
.
shift_space
, () => {
console
.
log
('Shift+Space 已经被按下')
})

当前按下的键

提供了一个特殊的属性 current,用于表示当前按下的所有键。

ts
import { 
useMagicKeys
,
whenever
} from '@vueuse/core'
const {
current
} =
useMagicKeys
()
console
.
log
(
current
) // Set { 'control', 'a' }
whenever
(
() =>
current
.
has
('a') && !
current
.
has
('b'),
() =>
console
.
log
('A 键被按下,但 B 键没有被按下'),
)

按键别名

ts
import { 
useMagicKeys
,
whenever
} from '@vueuse/core'
const {
shift_cool
} =
useMagicKeys
({
aliasMap
: {
cool
: 'space',
}, })
whenever
(
shift_cool
, () =>
console
.
log
('Shift + Space 已经被按下'))

默认情况下,我们有一些用于常见做法的预配置别名

有条件地禁用

你可能在应用程序中有一些 <input /> 元素,当用户聚焦在这些输入框上时,你不希望触发神奇按键处理。这里有一个使用 useActiveElementlogicAnd 的示例来实现这一点。

ts
import { 
useActiveElement
,
useMagicKeys
,
whenever
} from '@vueuse/core'
import {
logicAnd
} from '@vueuse/math'
const
activeElement
=
useActiveElement
()
const
notUsingInput
=
computed
(() =>
activeElement
.
value
?.
tagName
!== 'INPUT'
&&
activeElement
.
value
?.
tagName
!== 'TEXTAREA',)
const {
tab
} =
useMagicKeys
()
whenever
(
logicAnd
(
tab
,
notUsingInput
), () => {
console
.
log
('Tab 键被按下,不在输入框中!')
})

自定义事件处理程序

ts
import { 
useMagicKeys
,
whenever
} from '@vueuse/core'
const {
ctrl_s
} =
useMagicKeys
({
passive
: false,
onEventFired
(
e
) {
if (
e
.
ctrlKey
&&
e
.
key
=== 's' &&
e
.
type
=== 'keydown')
e
.
preventDefault
()
}, })
whenever
(
ctrl_s
, () =>
console
.
log
('Ctrl+S 已经被按下'))

⚠️ 不建议使用此用法,请谨慎使用。

响应式模式

默认情况下,useMagicKeys() 的值是 Ref<boolean>。如果你想在模板中使用对象,则可以将其设置为响应式模式。

ts
const 
keys
=
useMagicKeys
({
reactive
: true })
vue
<template>
  <
div
v-if="keys.shift">
你按住了 Shift 键! </
div
>
</template>

类型声明

显示类型声明
ts
export interface 
UseMagicKeysOptions
<
Reactive
extends boolean> {
/** * 返回一个响应式对象而不是 ref 对象 * * @default false */
reactive
?:
Reactive
/** * 监听事件的目标 * * @default window */
target
?:
MaybeRefOrGetter
<EventTarget>
/** * 键的别名映射,所有键都应为小写 * { target: keycode } * * @example { ctrl: "control" } * @default <预定义映射> */
aliasMap
?:
Record
<string, string>
/** * 注册被动监听器 * * @default true */
passive
?: boolean
/** * 自定义键盘按下/释放事件的处理程序。 * 当你想应用自定义逻辑时很有用。 * * 当使用 `e.preventDefault()` 时,你需要传递 `passive: false` 给 `useMagicKeys()`。 */
onEventFired
?: (
e
: KeyboardEvent) => void | boolean
} export interface MagicKeysInternal { /** * 当前按下的键的集合, * 存储原始的键码。 * * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key */
current
:
Set
<string>
} export type
UseMagicKeysReturn
<
Reactive
extends boolean> =
Readonly
<
Omit
<
Reactive
extends true
?
Record
<string, boolean>
:
Record
<string,
ComputedRef
<boolean>>,
keyof MagicKeysInternal > & MagicKeysInternal > /** * 响应式按键按下状态,具有神奇按键组合支持。 * * @see https://vueuse.org/useMagicKeys */ export declare function
useMagicKeys
(
options
?:
UseMagicKeysOptions
<false>,
):
UseMagicKeysReturn
<false>
export declare function
useMagicKeys
(
options
:
UseMagicKeysOptions
<true>,
):
UseMagicKeysReturn
<true>
export {
DefaultMagicKeysAliasMap
} from "./aliasMap"

源码

源码演示文档

贡献者

Anthony Fu
一纸忘忧
Anthony Fu
Arthur Darkstone
NoiseFan
NoiseFan
SerKo
keeplearning66
broBinChen
Sergey
IlyaL
babu-ch
Fernando Fernández
sibbng
jp-liu
Thiago Silveira
丶远方
Hartmut
Jelf
matrixbirds
lavolpecheprogramma
Kasper Seweryn
Thomas Gerbet
zzw
webfansplz
Ciro Lo Sapio
Alex Kozack

更新日志

554b7 - fix: update return types for createTemplatePromise, useMagicKeys, use… (#4963)
3f113 - fix: clearing of other keys after releasing alt (#5037)
d7f28 - fix: prevent incorrect clearing of other keys after releasing shift (#4916)
ab7ac - fix: correctly clear current pressed keys when releasing Shift (#4731)
7432f - feat(types): deprecate MaybeRef and MaybeRefOrGetter in favor of Vue's native (#4636)
b6947 - fix: fix key order issue on first use (#4505)
dd316 - feat: use passive event handlers everywhere is possible (#4477)
59f75 - feat(toValue): deprecate toValue from @vueuse/shared in favor of Vue's native
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
fccf2 - feat: upgrade deps (#3614)