Binding hotkeys to components with a custom Vue.js directive

v-hotkey - binding hotkeys for components

Vue.js offers a lot of possibilities regarding changes to the DOM. Also, Vue offers custom components and directives which are very useful when a specific task needs to be done. A good example of Vue's possibilities is the directive v-hotkey which allows the user to bind hotkeys so when triggered a specific action will take place, e.g. hide elements when pressing the buttons 'ctrl+p'.

Take a look at the following key combinations which you can use (one or more):

ctrl

alt

shift

meta (windows / command)

To see what we are talking about head to the live demo page and use your keyboard!

Example

Below you will find a small example on how to install and use the v-hotkey directive on a Vue project:

Install

// yarn yarn add v-hotkey // npm npm i --save v-hotkey

Usage

// main.js import Vue from 'vue' import VueHotkey from 'v-hotkey' Vue.use(VueHotkey) // *.vue file <template> <button v-hotkey="keymap" class="btn btn-default" :class="{'btn-lg' : size}" > Press "alt+q" to change size of the button </button> </template> <script> export default { data () { return { size: true, } }, methods: { toggle () { this.size = !this.size } }, computed { keymap () { return { // bind to hotkey 'alt+q': this.toggle } } } } </script>

Result:

To find what you need to get started head to GitHub where the source code of this project is available.