Vue Events
Handle user interactions in Vue applications
⚡ What are Vue Events?
Events let your Vue app respond to user actions like clicks, typing, or mouse movements. They make your application interactive and dynamic by triggering functions when users interact with elements.
<!-- Simple click event -->
<button @click="handleClick">Click Me</button>
Output:
Common Vue Events
Vue supports all standard DOM events. Events allow your application to respond to user interactions, making it feel alive and responsive. You can handle clicks, keyboard input, form submissions, mouse movements, and much more using Vue's event system.
Click Events
Handle button and element clicks
<button @click="doSomething">
Click
</button>
Keyboard Events
Respond to key presses
<input @keyup="handleKey">
Input Events
Track text input changes
<input @input="updateValue">
Mouse Events
Handle mouse interactions
<div @mouseover="showTooltip">
Hover me
</div>
🔹 Click Event Example
The most common event - responding to button clicks:
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const count = ref(0)
function increment() {
count.value++
}
</script>
Output:
Count: 0
🔹 Input Event Example
Capture and display user input in real-time:
<template>
<div>
<input @input="updateMessage" placeholder="Type something...">
<p>You typed: {{ message }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const message = ref('')
function updateMessage(event) {
message.value = event.target.value
}
</script>
Output:
You typed:
🔹 Mouse Events Example
Respond to mouse hover and leave actions:
<template>
<div>
<div
@mouseover="isHovered = true"
@mouseleave="isHovered = false"
:style="{ background: isHovered ? '#42b983' : '#ccc' }"
style="padding: 20px; text-align: center;"
>
{{ isHovered ? 'Hovering!' : 'Hover over me' }}
</div>
</div>
</template>
<script setup>
import { ref } from 'vue'
const isHovered = ref(false)
</script>
Output:
🔹 Keyboard Events Example
Detect when specific keys are pressed:
<template>
<div>
<input
@keyup.enter="submitForm"
placeholder="Press Enter to submit"
>
<p v-if="submitted">Form submitted!</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const submitted = ref(false)
function submitForm() {
submitted.value = true
setTimeout(() => submitted.value = false, 2000)
}
</script>
Output:
🔹 Multiple Events Example
Handle different events on the same element:
<template>
<div>
<button
@click="handleClick"
@dblclick="handleDoubleClick"
>
Click or Double Click
</button>
<p>{{ action }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const action = ref('No action yet')
function handleClick() {
action.value = 'Single clicked!'
}
function handleDoubleClick() {
action.value = 'Double clicked!'
}
</script>
Output:
No action yet