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>