Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Use basic event handling in Vue

    Rory SmithRory Smith

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

    vueVue.js
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:01 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.

    00:13 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.

    00:22 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.

    00:33 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.

    00:44 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.

    01:05 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.

    01:24 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.

    01:39 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.

    01:50 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.

    02:04 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.

    Discuss

    Discuss