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>