2

I want to use Vue.js to output which key was pressed.

This code works:

window.addEventListener('keydown', (event) => { 
   console.log(event.key);
});

Something like that e.g.:

<div @keydown="getKey">
</div>
getKey: function(event) {
   console.log(event.key)
}
1
  • 1
    This does work, but in input boxes and textareas...it doesn't seem to work in divs though. Why can't you use the first example though? Commented Mar 15, 2021 at 20:04

1 Answer 1

2

To achieve this you need to assign event listener to vue method:


created() {
  window.addEventListener('keydown', this.handleKeyDown);
},
beforeDestroy() {
  window.removeEventListener('keydown', this.handleKeyDown);
},
methods: {
  handleKeyDown(event) {
    console.log(event);
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man. Had a lot of trubble with "$refs.something" undefined! Ur solution helped wonders! I just moved the addEventListener to the mounted() lifecycle.

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.