Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 1083 of the free egghead.io lessons, plus get Vue.js content delivered directly to your inbox!

Existing egghead members will not see this. Sign in.

Use basic event handling in Vue

2:18 Vue.js lesson by

Let's use a range of events and their modifiers to look at the cool ways we can deal with event handlers in Vue.

Get the Code Now
click to level up

egghead.io comment guidelines


Let's use a range of events and their modifiers to look at the cool ways we can deal with event handlers in Vue.

Let's start by setting up a data value called "counter." Then in our template, we can set up a button with a click event, which increments that value.

Then, we'll show the value below. Now when we click the button, the counter updates. We can use other event types here apart from click. For example, mouse center.

We can also use an event handler to trigger a method. Let's set up an increment method, which shows a console log to us and then increments the counter.

Then, we can set up a button in our template, which triggers the increment method that we just made. Now, we can see that the value updated and we got a console log.

Let's try out something else. We'll set up a firstName value in our data, then let's make a logName method, which is just going to log the value that we just made. In our template, we can set up a form. When the submit event is fired, it's going to fire the method that we just created.

Within this form, we're going to set an input, which is bound to the firstName value that we made. When it changes in the input, it's going to change in our data too. Let's try out with an example name and we'll fire the submit. As you might expect, the entire page refreshes.

The usual way to deal with this is to use "prevent" default method of the event. That works fine, but in Vue, you can go up to your template and attach the "prevent" modifier. That handles it for us.

Aside from prevent, there's also "stop," which refers to stop propagation and several more including the "once" modifier, which will ensure that the event is only fired once.

Lastly, let's take a look at key modifiers. We'll set up a keyHandler method, which sets our firstName value to "Evan." In our input, we can set a "keyup" event.

Then, we can simply refer to the keys that we want to use to fire the event that we want. Now, when we press Ctlr + Alt + Shift + Down within our input, it's going to fire the keyHandle method.

Joel's Head
Why are we asking?