Pick key event with VueJS

1

How can I get a key event with Vue? I've already seen some examples on the site like:

<input @keyup.enter="submit">

But what I would like is some kind of listener where if the user presses a key call a function, without depending on button or input.

For example, I have a modal where I would like the user to hit ESC with the modal mode.

    
asked by anonymous 18.01.2018 / 18:47

1 answer

1

According to the Vuejs2 documentation , there are several keyboard modifiers, as you showed above in your @keyup.enter . In the case of the ESC key, there is .esc , such as @keyup.esc or @keydown.esc .

In order not to have to put this inside a input or button , it may not be the best way, but I've performed a demo below that will work whenever the ESC is pressed (or any key since it is set to% but there is a validation of the ESC key in the keyCode 27 case:

new Vue({
  el: '#app',
  created() {
    document.addEventListener('keyup', this.onEsc)
  },
  beforeDestroy() {
    document.removeEventListener('keyup', this.onEsc)
  },
  methods: {
    onEsc(e) {
      if (!e) e = window.event
      let keyCode = e.keyCode || e.which
      if (keyCode == '27') {
        console.log('Esc foi pressionado')
        console.log(e.target)
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script><divid="app">
  <h1>Criar um evento que seja disparado ao apertar a tecla ESC</h1>
  <h2>Aperte a tecla ESC e verifique o console.</h2>
</div>
    
11.02.2018 / 23:34