Vue Key Modifiers
In the previous post, we took a look at event modifiers. In this post, we will be looking at a more specialized category of event modifiers, namely so-called key modifiers.
As the name suggests, this category of event modifiers can be used with keyboard events.
Say that we have a text input, for example, and we want to do something if the user hits the Enter key, such as submitting a form or something like that. We could do that by using the keyup event with the v-on directive, and the enter key modifier.
<input type=”text” v-on:keyup.enter=”pressedEnter”>
The enter modifier ensures that the expression is only executed when the user releases the Enter key. I’ll just quickly add a method which shows an alert, just so that it is easy to test.
new Vue({
el: '#app',
methods: {
pressedEnter: function() {
alert("You pressed the Enter key!");
}
}
});
Running the code, you will see that if I enter a bunch of different characters, then nothing happens. But if I press the Enter key, we see the alert.
I just used the Enter key as an example. There are several other key modifiers built into Vue.js, such as tab, delete, esc and space, just to mention a few. And, if you need other keys than the available key modifiers, then you can use a number as the modifier instead. This number represents the character code, exactly as in vanilla JavaScript.
If I replace the enter key modifier with 13, which is the character code for the Enter key, then we should see that the alert is still showing.
<input type="text" v-on:keyup.13="pressedEnter">
In the previous post, I mentioned that modifiers can be chained. Perhaps I want the event listener to only be invoked when I press either the Enter og Space key.
First I will just replace 13 by enter as it improves readability.
<input type="text" v-on:keyup.enter="pressedEnter">
Then after the enter modifier, I can add another modifier by simply adding a dot followed by the name of the modifier. In this case, I will use the space modifier.
<input type="text" v-on:keyup.enter.space="pressedEnter">
What this does, is that the event listener is only invoked if I press either the Enter or Space key. Before taking the code for a spin, I should probably rename the event handler to something less misleading, as well as rephrase the alert message.
<input type="text" v-on:keyup.enter.space="pressedSomethingInteresting">
pressedSomethingInteresting: function() {
alert("You pressed the Enter or Space key!");
}
Now let’s test it out and verify that it works.
That’s all there is to key modifiers in Vue.js.
Here is what you will learn:
- How to build advanced Vue.js applications (including SPA)
- How Vue.js works under the hood
- Communicating with services through HTTP
- Managing state of large applications with Vuex
- ... and much more!
One comment on »Vue Key Modifiers«
Thank you very much for your great tutorials and videos about Vue.js!
I learned a lot from them