Introduction
Event handling lets your app respond when users click, type, or interact. It makes your app feel alive and useful.
Event handling lets your app respond when users click, type, or interact. It makes your app feel alive and useful.
<button @click="handleClick">Click me</button> <script setup> function handleClick() { alert('Button clicked!') } </script>
@eventName to listen to events in Vue templates.<input @input="onInputChange" placeholder="Type here" /> <script setup> function onInputChange(event) { console.log(event.target.value) } </script>
<div @mouseover="showTooltip">Hover me</div> <script setup> function showTooltip() { console.log('Tooltip shown') } </script>
<form @submit.prevent="submitForm"> <button type="submit">Send</button> </form> <script setup> function submitForm() { alert('Form submitted!') } </script>
This simple button counts how many times you click it. Each click updates the number shown.
<template> <button @click="increment">Clicked {{ count }} times</button> </template> <script setup> import { ref } from 'vue' const count = ref(0) function increment() { count.value++ } </script>
Always name your event handlers clearly to know what they do.
Use .prevent modifier to stop default browser actions like form reload.
Event handling connects user actions to your app's response, making it interactive.
Event handling lets your app react to user actions like clicks and typing.
Use @event in Vue templates to listen for events.
Define functions to run when events happen and update your app state.
@event shorthand or v-on:event to listen for events.@click, the recommended shorthand for click events in Vue templates.export default {
methods: {
sayHi() {
alert('Hi!')
}
}
}
<template>
<button @click="sayHi">Greet</button>
</template>
sayHi shows an alert with 'Hi!'. The button listens for click and calls this method.sayHi, so an alert box with 'Hi!' appears.<template>
<button @click="submitForm">Submit</button>
</template>
<script>
export default {
methods: {
submitform() {
console.log('Form submitted')
}
}
}
</script>
submitForm but the method is named submitform (lowercase f), causing a mismatch.<template>
<input @input="updateMessage" />
<p>Message: {{ message }}</p>
</template>
<script setup>
import { ref } from 'vue'
const message = ref('')
function updateMessage(event) {
// What should go here?
}
</script>
message is a ref, so to update its value, use message.value. The event object has the input value in event.target.value.message.value = event.target.value updates the reactive ref correctly.Pass the test and this pattern moves unknown