Vue.js
Beginner
1 min read
Event Handling with v-on
Example
<template>
<!-- Inline handler -->
<button @click="count++">Increment ({{ count }})</button>
<!-- Method reference -->
<button @click="resetCount">Reset</button>
<!-- Method call with argument -->
<button @click="addAmount(5)">Add 5</button>
<!-- Accessing the native event -->
<button @click="handleClick($event)">Log Event</button>
<!-- Event modifiers -->
<form @submit.prevent="onSubmit">
<input @keyup.enter="onSubmit" v-model="inputVal" />
<button type="submit">Submit</button>
</form>
<!-- Once modifier -->
<button @click.once="initOnce">Initialize (once)</button>
</template>
<script setup>
import { ref } from 'vue';
const count = ref(0);
const inputVal = ref('');
const resetCount = () => { count.value = 0; };
const addAmount = (n) => { count.value += n; };
const handleClick = (e) => { console.log(e.type, e.target); };
const onSubmit = () => { console.log('Submitted:', inputVal.value); };
const initOnce = () => { console.log('Runs only once'); };
</script>