1👍
✅
If you want to listen for global keyboard events you’ll need to add the listener to the window, otherwise you need focus on element that the event is dispatched from.
It’s just plain vanila js from there:
new Vue({
el: "#app",
data: {
one: 1
},
created() {
const component = this;
this.handler = function (e) {
e.keyCode == 38 && component.add()
e.keyCode == 40 && component.remove()
}
window.addEventListener('keyup', this.handler);
},
beforeDestroy() {
window.removeEventListener('keyup', this.handler);
},
methods: {
remove() {
this.one--;
},
add(){
this.one++;
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button @click="add">One</button>
<span> {{ one }}</span>
</div>
0👍
This is covered in the VueJS documentation.
Key Modifiers
When listening for keyboard events, we often need to check for
specific keys. Vue allows adding key modifiers for v-on when listening
for key events:
<!-- only call `vm.submit()` when the `key` is `Enter` --> <input v-on:keyup.enter="submit">
You can directly use any valid key names exposed via KeyboardEvent.key
as modifiers by converting them to kebab-case.<input v-on:keyup.page-down="onPageDown">
In the above example, the handler will only be called if $event.key is
equal to ‘PageDown’.
Source:stackexchange.com