useMagicKeys

useMagicKeys

リアクティブなキー押下状態を、魔法のキーコンビネーションサポートと共に提供します。

使用法

import { useMagicKeys } from '@vueuse/core'

const { shift, space, a /* 監視したいキー */ } = useMagicKeys()

watch(space, (v) => {
  if (v)
    console.log('スペースキーが押されました')
})

watchEffect(() => {
  if (shift.value && a.value)
    console.log('Shift + A が押されました')
})

すべての可能なキーコードを確認してください。

コンビネーション

キーを + または _ でつなげることで、魔法のようにコンビネーション(ショートカット/ホットキー)を使用できます。

import { useMagicKeys } from '@vueuse/core'

const keys = useMagicKeys()
const shiftCtrlA = keys['Shift+Ctrl+A']

watch(shiftCtrlA, (v) => {
  if (v)
    console.log('Shift + Ctrl + A が押されました')
})
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 関数を使用して短くすることもできます

import { useMagicKeys, whenever } from '@vueuse/core'

const keys = useMagicKeys()

whenever(keys.shift_space, () => {
  console.log('Shift+Space が押されました')
})

現在押されているキー

特別なプロパティ current が提供されており、現在押されているすべてのキーを表します。

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 は押されていません'),
)

キーのエイリアス化

import { useMagicKeys, whenever } from '@vueuse/core'

const { shift_cool } = useMagicKeys({
  aliasMap: {
    cool: 'space',
  },
})

whenever(shift_cool, () => console.log('Shift + Space が押されました'))

デフォルトで、一般的な用途のためにいくつかのエイリアスが事前設定されています

条件付き無効化

アプリに <input /> 要素があり、ユーザーがそれらの入力にフォーカスしているときにマジックキーの処理をトリガーしたくない場合があります。useActiveElementlogicAnd を使用した例があります。

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('入力外でタブが押されました!')
})

カスタムイベントハンドラー

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

import { useMagicKeys } from '@vueuse/core'
// ---cut---
const keys = useMagicKeys({ reactive: true })
<template>
  <div v-if="keys.shift">
    Shiftキーを押しています!
  </div>
</template>