0

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 class="Controller" @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?

0

4 Answers 4

2

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')
})
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

You may need to add the event parameter like this:

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

Comments

1

As you have non-input element, I don't think only @keypress event will work for <div> element. To make it work you have to add tabindex="0".

Live Demo :

new Vue({
  el: '#app',
  methods: {
    handleKeyPressed(e) {
      console.log(e)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
   <div class="Controller" @keypress="handleKeyPressed($event)" tabindex="0">Hello Vue JS!</div>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.