コンテンツへスキップ

useMagicKeys

カテゴリ
エクスポートサイズ
1.02 kB
最終更新
先週

リアクティブなキー押下状態と、マジックキーの組み合わせをサポートします。

この関数はProxyを使用します

IE 11以前ではサポートされていません

デモ

次のキーを押してテストしてください
V
u
e
U
s
e
Shift
Vue
Use
押されたキー

使い方

js
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'))

デフォルトでは、一般的なプラクティス用に事前設定されたエイリアスがいくつかあります。

条件付きで無効にする

アプリに<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 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<boolean>です。テンプレートでオブジェクトを使用する場合は、リアクティブモードに設定できます。

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

型宣言

型宣言を表示
typescript
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://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
>
/**
 * Reactive keys pressed state, with magical keys combination support.
 *
 * @see https://vueuse.dokyumento.jp/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
jp-liu
Thiago Silveira
丶远方
Hartmut
Jelf
matrixbirds
lavolpecheprogramma
Kasper Seweryn
Thomas Gerbet
zzw
webfansplz
Ciro Lo Sapio
Alex Kozack

変更履歴

v12.0.0-beta.1 2024/11/21
0a9ed - feat!: Vue 2 のサポートを削除、バンドルを最適化、クリーンアップ (#4349)
v10.7.0 2023/12/5
fccf2 - feat: 依存関係をアップグレード (#3614)
v10.0.0-beta.4 2023/4/13
4d757 - feat(types)!: MaybeComputedRefMaybeRefOrGetter にリネーム
v9.7.0 2022/12/16
21d24 - fix: @focus|@blur での 'current' もクリア (#2515)

MITライセンスの下でリリースされています。