跳到主要内容

useMagicKeys

分类
导出大小
1.17 kB
上次更改
上个月

响应式按键状态,支持魔法按键组合。

演示

按下以下按键进行测试
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
('space has been pressed')
})
watchEffect
(() => {
if (
shift
.
value
&&
a
.
value
)
console
.
log
('Shift + A have been pressed')
})

查看所有可能的键码

组合键

你可以通过使用 `+` 或 `_` 连接按键来神奇地使用组合键(快捷键/热键)。

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 have been pressed')
})
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 have been pressed')
})

你也可以使用 `whenever` 函数来使其更短。

ts
import { 
useMagicKeys
,
whenever
} from '@vueuse/core'
const
keys
=
useMagicKeys
()
whenever
(
keys
.
shift_space
, () => {
console
.
log
('Shift+Space have been pressed')
})

当前按下的按键

提供了一个特殊的属性 `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 is pressed but not B'),
)

按键别名

ts
import { 
useMagicKeys
,
whenever
} from '@vueuse/core'
const {
shift_cool
} =
useMagicKeys
({
aliasMap
: {
cool
: 'space',
}, })
whenever
(
shift_cool
, () =>
console
.
log
('Shift + Space have been pressed'))

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

有条件禁用

你的应用中可能有一些 `` 元素,并且你不希望在用户聚焦这些输入时触发魔法按键处理。这里有一个使用`useActiveElement``logicAnd`的示例。

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 has been pressed outside of inputs!')
})

自定义事件处理程序

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 have been pressed'))

⚠️ 不推荐此用法,请谨慎使用。

响应模式

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

ts
const 
keys
=
useMagicKeys
({
reactive
: true })
vue
<template>
  <
div
v-if="keys.shift">
You are holding the Shift key! </
div
>
</template>

类型声明

显示类型声明
ts
export interface 
UseMagicKeysOptions
<
Reactive
extends boolean> {
/** * Returns a reactive object instead of an object of refs * * @default false */
reactive
?:
Reactive
/** * Target for listening events * * @default window */
target
?:
MaybeRefOrGetter
<EventTarget>
/** * Alias map for keys, all the keys should be lowercase * { target: keycode } * * @example { ctrl: "control" } * @default <predefined-map> */
aliasMap
?:
Record
<string, string>
/** * Register passive listener * * @default true */
passive
?: boolean
/** * Custom event handler for keydown/keyup event. * Useful when you want to apply custom logic. * * When using `e.preventDefault()`, you will need to pass `passive: false` to useMagicKeys(). */
onEventFired
?: (
e
: KeyboardEvent) => void | boolean
} export interface MagicKeysInternal { /** * A Set of currently pressed keys, * Stores raw keyCodes. * * @see https://mdn.org.cn/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 > /** * Reactive keys pressed state, with magical keys combination support. * * @see https://vueuse.org.cn/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
NoiseFan
Arthur Darkstone
NoiseFan
SerKo
keeplearning66
broBinChen
Sergey
IlyaL
巴布-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: 更新 createTemplatePromise, useMagicKeys, use… 的返回类型 (#4963)
3f113 - 修复:释放 Alt 键后清除其他键的问题 (#5037)
v13.6.0
d7f28 - 修复:防止释放 Shift 键后错误清除其他键 (#4916)
v13.2.0
ab7ac - 修复:在释放 Shift 键时正确清除当前按下的键 (#4731)
v12.8.0
7432f - feat(types): 废弃 MaybeRefMaybeRefOrGetter,转而使用 Vue 的原生类型 (#4636)
v12.5.0
b6947 - 修复:解决首次使用时按键顺序问题 (#4505)
v12.4.0
dd316 - feat: 尽可能在所有地方使用被动事件处理程序 (#4477)
v12.3.0
59f75 - feat(toValue): 废弃 @vueuse/shared 中的 toValue,转而使用 Vue 的原生函数
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)
v10.7.0
fccf2 - feat: 升级依赖 (#3614)

根据 MIT 许可证发布。