Vue.js Events

By

Vue.js lets you intercept any DOM event with the v-on directive (or @ shorthand). Learn parameters, $event, and event modifiers in Vue 3.

~~~

What are Vue.js events

Vue.js allows us to intercept any DOM event by using the v-on directive on an element. This applies to Vue 3 the same way it did in older versions, with the same @ shorthand.

If we want to do something when a click event happens in this element:

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

we add a v-on directive:

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

Vue also offers a very convenient alternative syntax for this:

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

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

handleClick is a method attached to the component. With Composition API:

<script setup>
function handleClick(event) {
  console.log(event)
}
</script>

Or with Options API:

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

Methods are explained more in detail in my Vue Methods tutorial.

What you need to know here is that you can pass parameters from events: @click="handleClick(param)" and they will be received inside the method.

Access the original event object

In many cases, you will want to perform an action on the event object or look up some property in it. How can you access it?

Use the special $event directive:

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

<script setup>
function handleClick(event) {
  console.log(event)
}
</script>

and if you already pass a variable:

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

<script setup>
function handleClick(text, event) {
  console.log(text)
  console.log(event)
}
</script>

From there you could call event.preventDefault(), but there’s a better way: event modifiers

Event modifiers

Instead of messing with DOM “things” in your methods, tell Vue to handle things for you:

All those options can be combined by appending on modifier after the other.

Vue 3 dropped the .native modifier. A @click on a component falls through to its root element as a native listener, as long as the component has a single root and does not declare click in emits. You don’t need .native anymore.

For more on propagation, bubbling/capturing see my JavaScript events guide. If you’re wiring handlers that then update state, watchers are useful when a change must trigger a side effect.

Tagged: Vue.js · All topics

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about vue: