Vue.js provides a convenient way to handle DOM events using the v-on directive on an element. Being able to intercept events is essential in making Vue components interactive.

What are Vue.js events?

With Vue.js, we can intercept any DOM event using the v-on directive on an element. For example, if we want to perform something when a click event occurs on an element:

<template>
  <a>Click me!</a>
</template>

We can add the v-on directive:

<template>
  <a v-on:click="handleClick">Click me!</a>
</template>

Vue also provides an alternative syntax for this:

<template>
  <a @click="handleClick">Click me!</a>
</template>

You can choose to use parentheses or not. @click="handleClick" is equivalent to @click="handleClick()".

The handleClick method is attached to the component:

<script>
export default {
  methods: {
    handleClick: function(event) {
      console.log(event);
    }
  }
}
</script>

If you want to learn more about Vue methods, check out my Vue Methods tutorial.

Accessing the original event object

In many cases, you may need to perform an action on the event object or retrieve some properties from it. How can you access the event object?

You can use the special $event directive:

<template>
  <a @click="handleClick($event)">Click me!</a>
</template>

<script>
export default {
  methods: {
    handleClick: function(event) {
      console.log(event);
    }
  }
}
</script>

If you want to pass additional variables:

<template>
  <a @click="handleClick('something', $event)">Click me!</a>
</template>

<script>
export default {
  methods: {
    handleClick: function(text, event) {
      console.log(text);
      console.log(event);
    }
  }
}
</script>

From there, you can call event.preventDefault(), but there’s a more elegant solution: event modifiers.

Event modifiers

Instead of manipulating the DOM directly in your methods, you can instruct Vue to handle them for you:

  • @click.prevent calls event.preventDefault()
  • @click.stop calls event.stopPropagation()
  • @click.passive makes use of the passive option of addEventListener
  • @click.capture uses event capturing instead of event bubbling
  • @click.self ensures the click event was not bubbled from a child event, but directly happened on that element
  • @click.once triggers the event only once

You can combine multiple modifiers by appending them one after the other.

For more information on event propagation, bubbling, and capturing, refer to my JavaScript events guide.