🎓 A1Learner
🔍
0 of 50 lessons completed

Vue Event Handling

Event handling runs code when something happens on the page. An event is a signal, like a click on a button.

An inline handler

The click adds one to count.

<button @click="count++">Add</button>

A method handler

The click runs the reset function.

<button @click="reset">Reset</button>

The method

reset sets count back to zero.

function reset() {
  count.value = 0
}

Example

<script setup>
import { ref } from 'vue'
const count = ref(0)
function reset() {
  count.value = 0
}
</script>
<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="count++">Add</button>
    <button @click="reset">Reset</button>
  </div>
</template>

Key points

  • The v-on directive listens for an event, with @ as its short form.
  • An inline handler is a short expression written in the template.
  • A method handler is a named function written in script setup.
  • A method handler keeps longer logic out of the template.
  • The handler runs each time the event fires.

In this example, count starts at zero. The Add button uses an inline handler to add one. The Reset button calls the reset method. reset sets count back to zero. The paragraph always shows the current count.

Note

A handler can read and change state, like a ref value.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Where does a method handler live?