0
0
Vueframework~5 mins

Why event handling matters in Vue

Choose your learning style9 modes available
Introduction

Event handling lets your app respond when users click, type, or interact. It makes your app feel alive and useful.

When a user clicks a button to submit a form
When a user types in a search box and you want to show suggestions
When a user hovers over an image to show more details
When a user scrolls and you want to load more content
When a user presses a key to trigger a shortcut
Syntax
Vue
<button @click="handleClick">Click me</button>

<script setup>
function handleClick() {
  alert('Button clicked!')
}
</script>
Use @eventName to listen to events in Vue templates.
The event handler is a function defined in your script.
Examples
This listens to typing in an input box and logs what you type.
Vue
<input @input="onInputChange" placeholder="Type here" />

<script setup>
function onInputChange(event) {
  console.log(event.target.value)
}
</script>
This runs code when you move your mouse over the box.
Vue
<div @mouseover="showTooltip">Hover me</div>

<script setup>
function showTooltip() {
  console.log('Tooltip shown')
}
</script>
This handles form submission and prevents the page from reloading.
Vue
<form @submit.prevent="submitForm">
  <button type="submit">Send</button>
</form>

<script setup>
function submitForm() {
  alert('Form submitted!')
}
</script>
Sample Program

This simple button counts how many times you click it. Each click updates the number shown.

Vue
<template>
  <button @click="increment">Clicked {{ count }} times</button>
</template>

<script setup>
import { ref } from 'vue'

const count = ref(0)
function increment() {
  count.value++
}
</script>
OutputSuccess
Important Notes

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.

Summary

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.