[Vuejs]-How to create a listener that's listening to multiple shortcuts Ctrl + [1-9]?

3πŸ‘

F1-F9 keys are in a range of possible numerals, so just use that range in a single if statement:

created () {
  window.addEventListener('keydown', this.switchTab)
},

methods: {
  switchTab (event) {
    // F1 = 112, F12 = 123 
    if (event.ctrlKey && event.keyCode > 111 && event.keyCode < 124   ) {
     this.changeRoute (event)        
    }
  },
  changeRoute (event) {
    console.log(event.key)
  }
}

Vanilla JS demo:

   // Try pressing CTRL+F1 to F12 (give the demo window focus first)
document.addEventListener('keydown', e => {
    console.log( e.keyCode );
    return false;
})
πŸ‘€vsync

1πŸ‘

if you wan’t to still be explicit, you could use a switch statement:

if(event.ctrlKey) {
    switch(event.keyCode) {
        case 49: case 50: case 51: case 52: case 53: 
        case 54: case 55: case 56: case 57: case 58:
            this.changeRoute(event);
            break;
    }
}
πŸ‘€Jon List

Leave a comment