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 } }) }); }
You might need to add removeEventListener() on beforeDestroy().
LikeLike
Very important : do not forget to remove the listener when the component is destroyed !
Note that you will need to define the event callback in a named function to be properly able to target the listener to be removed (the methods section of the component is a good place to define it.)
“`
beforeDestroy: function () {
window.removeEventListener(‘keyup’, this.handleKeyup)
}
“`
LikeLike