Tutorial

Vue Event Handling Methods

Published on February 28, 2020
Default avatar

By Jim Toth

Vue Event Handling Methods

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Often when we are developing user interfaces for the web we would like to customize the behavior of DOM events to provide a richer user experience. Form submissions, button clicks, and even scrolling all have associated DOM events that can be listened for and handled by our code. Whether we want to prevent or change the default behavior of these events, we need to listen to them and consume these events to achieve our desired behavior.

Vue provides the v-on directive which allows us to listen for and customize DOM events on our HTML elements by providing it with the name of the event. For example, v-on:click allows us to consume the click DOM event. Check out Mozilla’s full list of DOM events for more possibilities.

Inline Event Handling

Using the v-on directive we can listen for the click event on a button and increment a simple counter that tracks the amount of clicks. By providing JavaScript code to the v-on directive, we’re able to have it executed in the context of our component whenever the click event is triggered.

InlineMethodComponent.vue
<template>
  <div>
    <h2>InlineMethodComponent</h2>
    <button v-on:click="clicked += 1">
      Clicked {{ clicked }} times
    </button>
  </div>
</template>

<script>
export default {
  name: 'InlineMethodComponent',
  data: function () {
    return {
      clicked: 0
    }
  }
}
</script>

Component Methods

Now that we’re able to handle DOM events, we’ll want to begin implementing logic that becomes more complex. It would be quite cumbersome and bad practice to add a bunch of complex logic inside the v-on directive. Luckily, Vue allows us to define event handling methods on the component. All we need to do is pass the name of the component’s method to the v-on directive:

SimpleMethodComponent.vue
<template>
  <div>
    <h2>SimpleMethodComponent</h2>
    <button v-on:click="log">
      Click Me
    </button>
  </div>
</template>

<script>
export default {
  name: 'SimpleMethodComponent',
  methods: {
    log() {
      console.log('Button clicked!');
    }
  }
}
</script>

Inline Method Calls

Sometimes we want to be able to pass information to our method calls or even consume the DOM event itself. Instead of passing the name of a method to the v-on directive, we can instead pass a call to the method itself, passing in any information we desire. We can also use the special variable $event which contains the DOM event itself.

InlineMethodCallComponent.vue
<template>
  <div>
    <h2>InlineMethodCallComponent</h2>
    <button v-on:click="log('clicked!', $event)">
      Click Me
    </button>
  </div>
</template>

<script>
export default {
  name: 'InlineMethodCallComponent',
  methods: {
    log(msg, event) {
      console.log(event.target.tagName, msg);
    }
  }
}
</script>

Event Method Modifiers

There are times where we’d like to modify or even prevent the default behavior of DOM events. Vue provides us with some modifiers that we can chain to the name of the event that we provide to the v-on directive.

For example, if we had a form containing a button with type Submit, a user’s click would refresh the page. With single page applications (SPAs), we want to avoid full page reloads. To do this we could chain the .prevent modifier which prevents the event from reloading the page by calling event.preventDefault(). The .stop modifier also completely halts the default behavior of the DOM event by calling event.stopPropagation() which often needs to be called in custom event handlers.

MethodCallModifiersComponent.vue
<template>
  <div>
    <h2>MethodCallModifiersComponent</h2>
    <form
      v-on:submit.stop.prevent="log('clicked!', $event)">
      <button type="Submit">
        Click Me
      </button>
    </form>
  </div>
</template>

<script>
export default {
  name: 'MethodCallModifiersComponent',
  methods: {
    log(msg, event) {
      console.log(event.target.tagName, msg);
    }
  }
}
</script>

Event Method Key Modifiers

Sometimes we have DOM events that are triggered by keyboard presses. Vue provides us with event modifiers tailored for key-based events.

For example, if we had an input element, we could listen to key presses for both Enter and Esc. By customizing this behavior we could allow Enter to call our log() method and allow Escape to provide a quick way for the user to reset their input.

MethodCallKeyModifiersComponent.vue
<template>
  <div>
    <h2>MethodCallKeyModifiersComponent</h2>
    <input
      placeholder="Press Enter"
      v-on:keyup.esc.stop="clear"
      v-on:keyup.enter.stop="log"
    />
  </div>
</template>

<script>
export default {
  name: 'MethodCallKeyModifiersComponent',
  methods: {
    log(event) {
      console.log(
        event.target.tagName,
        event.type,
        event.key,
        event.target.value
      );
    },
    clear(event) {
      event.target.value = '';
    }
  }
}
</script>

Wrapping Up

Thanks to the v-on directive we’re able to intercept and customize the behavior of DOM events in a pain-free manner. Since these events are tied to an individual component we don’t have to worry to tell our event handlers to stop listening - they are destroyed when the component is destroyed. No clean-up!

Make sure to check out the full reference for both event modifiers and key modifiers to discover the possibilities they allow!

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Jim Toth

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel