上下キーで移動&Enterキーで選択イベント

VueのonMouted、onUnmoutend の記述があるけどそこはメインじゃないのでスルーで。

const onKeyDown = (e: KeyboardEvent) => {
  const { isComposing, key, target } = e
  if (isComposing) return 
  if (
    !(target instanceof HTMLElement) ||
    target.tagName === 'INPUT' ||
    target.tagName === 'TEXTAREA'
  ) 
    return
  if (key === 'ArrowDown' || key === 'ArrowUp') {
    e.preventDefault()
  }
}
const onKeyUp = (e: KeyboardEvent) => {
  const { isComposing, key, target } = e
  if (isComposing) return
  if (
    !(target instanceof HTMLElement) ||
    target.tagName === 'INPUT' ||
    target.tagName === 'TEXTAREA'
  )
    return
  if (key === 'ArrowDown' || key === 'ArrowUp' || key === 'Enter') {
    e.preventDefault()
    console.log(key, '処理')
  }
}

onMounted(() => {
  document.addEventListener('keydown', onKeyDown)
  document.addEventListener('keyup', onKeyUp)
})
onUnmounted(() => {
  document.removeEventListener('keydown', onKeyDown)
  document.removeEventListener('keyup', onKeyUp)
})

ポイントは
・isComposing をみてIME変換中の操作だった場合はスルー
・input or textarea 内の操作に反応したくないのでスルー
・target は instanceof HTMLElement チェックをいれて typescript のエラー回避
・keydown はデフォルトイベント解除のみ、keyup時に処理