Vue Js 2 – Keyboard Events
In this post we are going to talk about keyboard events. We have access to events like keydown, keypress and keyup. I want to take a look at those events and some keyboard events modifiers in this post.
All codes here;
<title>Vue Js 2 Tutorials for Learners</title>
<input type="text" v-on:keyup.enter="logName"/>
<input type="text" v-on:keyup.ctrl.enter="logJob"/>
alert('You are writing your Name now.');
alert('You are writing your Job now.');
In index.html file, I’m creating a couple of labels. We are going to listen out for events on these fields. The events have what I listen for are the key or events.
Now I’m adding those events on as by v-on:keyup. The it is going to be equal to something and going to be equal to some kind of function. Now we just give these functions that we want to fire a name I’II call this one logName and logJob.
When we do a keep event on name input field, it is going to find this function on the instance in app.js file.
I’m going to do two very simple methods in this method object in app.js file, vue instance.
In logName and logJob, I’m writing alert and say if these input fields start to write with keyboard, show alert and say these;
alert(‘You are writing your Name now.’);
alert(‘You are writing your Job now.’);
Now we’re listening keyup event in our website. Every time I type something, the keyup event wiil fire and show alert on our browser.
But what if we don’t want this to output every single time? For example I want to listen with press Enter on keyboard only and fire this function.
We can dı that by adding on a modifier. This modifier is called enter;
<input type=”text” v-on:keyup.enter=”logName” />
<input type=”text” v-on:keyup.enter=”logJob”/>
We are listening enter keyboard in name and job input fields anymore. Alert show only press enter. It’s very simple and useful.
I want to show you one more thing. We can tack on together, we can chain them together these different modifiers.
For example; I want to use enter keyboard in job input only press CTRL + ENTER together. Just add ctrl in code and test it. Very simple 🙂
<input type=”text” v-on:keyup.ctrl.enter=”logJob”/>