5

[Vue.js] Keyboard Event (Arrow Key Example)

 3 years ago
source link: http://siongui.github.io/2017/12/06/vuejs-keyboard-event-arrow-key-example/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

[Vue.js] Keyboard Event (Arrow Key Example)

December 06, 2017

See demo first. Focus on the following textarea element and press arrow keys on your keyboard. You will see the keyCode of the arrow key pressed by you.

The following is the source code for above demo.

HTML:

<div id="vueapp">
  <textarea @keyup.arrow-keys="show">{{ keypressed }}</textarea>
</div>

<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>

We use key modifiers [3] to listen to the keyup event of textarea element. When textarea element is focused and users press any arrow key, the keyCode of the arrow key will be shown in the textarea.

JavaScript:

'use strict';

Vue.config.keyCodes = {
  "arrow-keys": [37, 38, 39, 40]
};

var app = new Vue({
  el: '#vueapp',
  data: {
    keypressed: ""
  },
  methods: {
    show: function (event) {
      this.keypressed += event.keyCode;
    }
  }
});

There are four arrow keys on the keyboard. We need to define custom key alias for the arrow keys in the keyCodes in Vue.config. The keyCodes of arrow keys are from 37~40, so we use array of numbers to define key alias.

Note that the following syntax in Vue.config does not work:

arrowKeys: [37, 38, 39, 40]

The correct syntax is:

"arrow-keys": [37, 38, 39, 40]

When users press arrow key in textarea element, the show method will be executed and the keyCode of the corresponding arrow key will be appended to the textarea.


Tested on:

  • Chromium Version 62.0.3202.94 (Official Build) Built on Ubuntu , running on Ubuntu 17.04 (64-bit)
  • Vue.js 2.5.9

References:

[1]JavaScript Keyboard Event (Arrow Key Example)

[2]JavaScript Arrow Key Example via event.key in Keyboard Event

[4]keyCodes - Global Config - API - Vue.js


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK