Using Vue 2.5 I'm trying to hide a component if the esc
key is pressed.
Inspired by the documentation on key modifiers, I wrote the following code but with no effect (for the moment I'm not hiding, just displaying a message):
Vue.component('my-component', {
data: function () {
return {isVisible:true,
message:'no key pressed'}
},
template: '<div v-on:keyup.esc="myMethod" v-if="isVisible">This is my component<div>{{message}}</div>',
methods:{
myMethod : function(){
this.message = 'esc key pressed'
//My hiding action...
}
}
})
new Vue({
el: '#app',
data: {
}
})
Fiddle
EDIT : looks like the issue is related to the fact I'm trying to implement this on a regular div, not on an input as it's usually used
I think you should add
created: function() {
document.addEventListener('keyup', this.myMethod);
}
And in your method:
myMethod(event) {
if (event.keyCode === 27) {
this.message = 'esc key pressed'
console.log('esc key pressed');
}
}
Here is working example: https://jsfiddle.net/uzxugzo7/9/
Also, don't forget to destroy it, to prevent memory leaks
destroyed: function() {
document.removeEventListener('keyup', this.myMethod);
}
To make static elements accessible to keyboard event use tabindex
<div v-on:keyup.esc="myMethod" tabindex="0" v-if="isVisible">This is my component<div>{{message}}</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With