Javascript is required
·
1 min read

Vue Tip: Chaining Event Modifiers

Vue Tip: Chaining Event Modifiers Image

Most likely you have already called event.preventDefault() or event.stopPropagation() inside event handlers:

Component.vue
1<script setup lang="ts">
2function onClick(event: Event) {
3  event.preventDefault()
4
5  // ... some other logic
6}
7</script>
8
9<template>
10  <button @click="onClick">Click me</button>
11</template>

As you can see, you can easily implement this functionality using methods. but as an alternative, Vue provides event modifiers.

Using these modifiers your method contains only the data logic and the DOM event details are part of the template:

Component.vue
1<script setup lang="ts">
2function onClick(event: Event) {
3  // ... some other logic
4}
5</script>
6
7<template>
8  <button @click.prevent="onClick">Click me</button>
9</template>

Vue provides the following event modifiers:

  • .stop
  • .prevent
  • .self
  • .capture
  • .once
  • .passive

You can also chain modifiers:

Component.vue
1<script setup lang="ts">
2function onClick(event: Event) {
3  // ... some other logic
4}
5</script>
6
7<template>
8  <button @click.stop.prevent="onClick">Click me</button>
9</template>

Order matters

The sequence of modifiers is significant as the corresponding code is generated in the exact order they appear.

An example: Using @click.prevent.self will prevent click's default action on the element itself and its children, while @click.self.prevent will only prevent click's default action on the element itself.

Warning

Do not use .passive and .prevent together.

By using the .passive modifier, you are effectively signaling to the browser that you have no intention of preventing the default behavior of the event.

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.