Ilkar
Ilkar

Reputation: 2167

VUE how to evoke keydown method

i would like to create method which will run when any keyboard key will down, and then i will check which key was down. What is important, it should run even if focus will be out of any inputs and so on.

I've created evoking when focus is in 'input' using:

 @keydown.native="keymonitor"

but i would like to evoke 'keymonitor' method when there is no focus on input, but coursor is anywhere on website and focus is anywhere.

How to do it? if a add

@keydown.native="keymonitor"

to general div or body, it doesn't work.

Thanks for help.

Upvotes: 1

Views: 404

Answers (2)

Dev Catalin
Dev Catalin

Reputation: 1325

You can use the keydown event.

Here is an example within a Vue component:

<template>
  <div>
    {{ lastKeyPressed }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      lastKeyPressed: null,
    }
  },
  created() {
    window.addEventListener("keydown", (e) => {
      this.lastKeyPressed = e.keyCode;
      console.log(e.keyCode);
    });
  }
};
</script>

Be sure to use an arrow function on the addEventListener callback to ensure that this keyword works correctly, see this for other examples.

Upvotes: 0

Majed Badawi
Majed Badawi

Reputation: 28404

You can use the normal EventTarget#addEventListener on window as follows:

new Vue({
  el:"#app",
  created() {
    window.addEventListener('keydown', e => {
      console.log(e.keyCode);
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app"></div>

Upvotes: 1

Related Questions