Reputation: 119
How to click a button not only directly clicking mouse, but pressing a button on a keyboard (in this case, its a keyboard button with a value "1" that has
event.key` = 1)???
new Vue({
el: "#app",
data: {
one: 1
},
methods: {
add(){
this.one++;
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button v-on:1 @click="add">One</button>
<span> {{ one }}</span>
</div>
Upvotes: 0
Views: 359
Reputation: 1273
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'.
Upvotes: 0
Reputation: 296
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>
Upvotes: 1