Vue ShortKey

Vue-ShortKey - plugin for VueJS 2.x accepts shortcuts globaly and in a single listener.

Install

npm install vue-shortkey --save

Usage

Vue.use(require('vue-shortkey'))
JavaScript

Add the shortkey directive to the elements that accept the shortcut.
The shortkey must have explicitly which keys will be used.

Running functions

The code below ensures that the key combination ctrl + alt + o will perform the 'theAction' method.

<button v-shortkey="['ctrl', 'alt', 'o']" @shortkey="theAction()">Open</button>
HTML

The function in the modifier @shortkey will be called repeatedly while the key is pressed. To call the function only once, use the once modifier

<button v-shortkey.once="['ctrl', 'alt', 'o']" @shortkey="theAction()">Open</button>
HTML

Setting the focus

You can point the focus with the shortcut easily.
The code below reserves the ALT + I key to set the focus to the input element.

<input type="text" v-shortkey.focus="['alt', 'i']" v-model="name" />
HTML

Push button

Sometimes you may need a shortcut works as a push button. In these cases, insert the "push" modifier

The example below shows how to do this

<tooltip v-shortkey.push="['f3']" @shortkey="toggleToolTip"></tooltip>
HTML

You can make any combination of keys as well as reserve a single key.

<input type="text" v-shortkey="['q']" @shortkey="foo()"/>
<button v-shortkey="['ctrl', 'p']" @shortkey="bar()"></button>
<button v-shortkey="['f1']" @shortkey="help()"></button>
<textarea v-shortkey="['ctrl', 'v']" @shortkey="dontPaste()"></textarea>
HTML

Avoided fields

You can avoid shortcuts within fields if you really need it. This can be done in two ways:

  • Preventing a given element from executing the shortcut by adding the v-shortkey.avoid tag in the body of the element
<textarea v-shortkey.avoid></textaea>
HTML
  • Generalizing type of element that will not perform shortcut. To do this, insert a list of elements in the global method.
Vue.use('vue-shortkey', { prevent: ['input', 'textarea'] })
JavaScript
  • Or even by class
Vue.use('vue-shortkey', { prevent: ['.my-class-name', 'textarea.class-of-textarea'] })
JavaScript

Other uses

With the dynamism offered by Vue, you can easily create shortcuts dynamically

<li v-for="(ctx, item) in itens">
  <a
    href="https://vuejs.org"
    target="_blank"
    v-shortkey="['f' + (item + 1)]"
    @shortkey="testa(item)"
    @click="testa()">
      F {{ item }}
  </a>
</li>
HTML

Unit Test

npm test

GitHub

— Read More

Latest commit to the undefined branch on unknown
Download as zip