Tutorial

Vue Event Handling Methods

Vue.js

While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using 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!

0 Comments

Creative Commons License