The v-on Directive
The v-on directive listens for an event on an element. An event is something that happens, like a click on a button.
Listen for a click
The count starts at 0.
<button @click="count++">Add</button>Call a named function
The count starts at 0. The button calls the add function.
<button @click="add">Add</button>Listen on any element
The count starts at 0.
<p @click="count++">{{ count }}</p>Example
<script setup>
import { ref } from 'vue'
const count = ref(0)
function add() {
count.value++
}
</script>
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="add">Add</button>
</div>
</template>
Key points
- Write v-on:click to listen for a click.
- The short form is an at sign, like @click.
- Give the event a function to run, like @click="add".
- The function can change a ref, so the page updates.
- v-on works for many events, like click and input.
In this example, the script makes a count of 0 and an add function. The function adds 1 to count.value. The template shows the count and a button. The button listens for a click with @click. The page first shows Count: 0. One click makes the count 1, so the page shows Count: 1.
Note
The function runs when the event happens, not when the page first shows.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does @click do?