A simple method for adding keyboard shortcuts to your components is to do the following:
-
- Add the ‘mounted’ lifecycle event hook to your component
- Add an event listener to the ‘window’ object and have it listen for the ‘keyup’ event
- Check for the proper keyboard key code and system modifier key (command/control, option/alt, shift, etc.) combination
- Execute custom logic in response
Example: here the key combination ‘alt+n’ is being checked for
mounted: function () {
this.$nextTick(function () {
window.addEventListener('keyup', event => {
if(event.altKey && event.keyCode === 78){
//TODO: do/call something here
}
})
});
}
