I have a variable that I want to be setted to 1 when alt key is pressed and to 0 when is not, but the result is that Vue perform only @keydown.alt.
I tried with the enter key, and it works perfectly, toggling between the two states, but I can't figure out why it doesn't with alt key.
@keydown.alt="scheda++"
@keyup.alt="scheda--"
From Vuejs documentation:
Note that modifier keys are different from regular keys and when used with keyup events, they have to be pressed when the event is emitted. In other words, keyup.ctrl will only trigger if you release a key while holding down ctrl. It won’t trigger if you release the ctrl key alone. If you do want such behaviour, use the keyCode for ctrl instead: keyup.17
But for Alt there is one more problem if you are using Windows.
On Windows systems, the window interprets hitting Alt as wanting to open the window's menu, and the keyup
is not triggered anymore. We want to prevent the default behavior and we can do this with event.preventDefault()
, or, in Vue world, the .prevent
event modifier.
new Vue({
el: '#app',
data: {
counter: 0
},
methods: {
increment: function() {
console.log('inc')
this.counter += 1;
},
decrement: function() {
console.log('dec')
this.counter -= 1;
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input @keydown.18.prevent="increment()" @keyup.18.prevent="decrement()">
<p >{{ counter }}</p>
</div>