Pick up keystroke event with Vuejs

Asked

Viewed 780 times

1

How can I catch a key event with Vue? I’ve seen some examples on the site like:

<input @keyup.enter="submit">

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

For example, I have a modal where I would like the user to press the ESC button the modal to close.

1 answer

1


In accordance with the documentation of Vuejs2, there are several keyboard modifiers, as you showed up on your @keyup.enter. In the case of the ESC button, there is the .esc, such as, for example, @keyup.esc or @keydown.esc.

So I don’t have to put this inside a input or button, may not be the best way, but I performed a demo below that will work whenever the ESC is pressed (or any key, as it is set to keyup, but there is a validation of the ESC key in the case keycode 27):

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>
<div id="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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.