Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuejs : how to hide a component <div> on keyup escape?

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

like image 903
Sebastien D Avatar asked Dec 11 '22 07:12

Sebastien D


2 Answers

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);
}
like image 170
Stefan Tanevski Avatar answered Dec 16 '22 16:12

Stefan Tanevski


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>
like image 20
Vamsi Krishna Avatar answered Dec 16 '22 17:12

Vamsi Krishna