Home > Blockchain >  Detecting key stroke in vue.js
Detecting key stroke in vue.js

Time:08-02

How can I get an event handler to be fired whenever a user taps on any keyboard key?

I've tried in my main component:

<template>
  <div  @keypress="handleKeyPressed">

And later on in the methods:

handleKeyPressed(e) {
      console.log(e)
}

However, when I press any key - I don't see a log in the console and it seems that no key stroke is captured by vue.js

How can I get an event handler to be fired whenever a user taps on any keyboard key?

CodePudding user response:

You can try window.addEventListener('keypress', yourListenerCallback, options) for listen keypress event on created hook and window.removeEventListener('keypress', yourListenerCallback, options) on beforeDestroy hook for remove your listener

CodePudding user response:

You may need to add the event parameter like this:

<div  @keypress="handleKeyPressed($event)">

CodePudding user response:

While some of the other answers might work for you, I've started using a composable made available from the vueuse library.

https://vueuse.org/core/usemagickeys/

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

const keys = useMagicKeys()

whenever(keys.shift_space, () => {
  console.log('Shift Space have been pressed')
})
  • Related