[Vue.js] Keyboard Event (Arrow Key Example)
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/vue@2.5.9/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 |
[3] | Key Modifiers - Event Handling — Vue.js |
[4] | keyCodes - Global Config - API - Vue.js |