Sometimes you need to know exactly what happened when a user interacts with your page. Accessing the native event object lets you see details like which key was pressed or where the mouse clicked.
0
0
Accessing the native event object in Vue
Introduction
When you want to know which key a user pressed in an input box.
When you need to find the mouse position during a click.
When you want to prevent the default browser action on a button click.
When you want to check if a modifier key like Shift or Ctrl was held during an event.
Syntax
Vue
<template> <button @click="handleClick">Click me</button> </template> <script setup> function handleClick(event) { // event is the native event object } </script>
The event object is automatically passed as the first argument to your event handler.
You can access properties like event.target, event.type, event.preventDefault(), and more.
Examples
This example logs the key the user pressed inside an input box.
Vue
<template> <input @keydown="onKeyDown" /> </template> <script setup> function onKeyDown(event) { console.log('Key pressed:', event.key); } </script>
This example prevents the default button action and shows an alert instead.
Vue
<template> <button @click="onClick">Click me</button> </template> <script setup> function onClick(event) { event.preventDefault(); alert('Default action prevented!'); } </script>
This example logs the mouse position inside a div as you move the mouse.
Vue
<template> <div @mousemove="onMouseMove">Move your mouse here</div> </template> <script setup> function onMouseMove(event) { console.log(`Mouse at: (${event.clientX}, ${event.clientY})`); } </script>
Sample Program
This Vue component shows an input box. When you press a key, it updates the text below to show which key was pressed by accessing the native event object.
Vue
<template> <input @keydown="handleKeyDown" placeholder="Press any key" /> <p>Last key pressed: {{ lastKey }}</p> </template> <script setup> import { ref } from 'vue'; const lastKey = ref('None'); function handleKeyDown(event) { lastKey.value = event.key; } </script>
OutputSuccess
Important Notes
Always name the event parameter (commonly 'event' or 'e') to access the native event object.
You can call event.preventDefault() to stop the browser's default behavior.
Use event.target to find which element triggered the event.
Summary
The native event object gives you details about user actions.
Vue automatically passes this event object to your event handlers.
You can use it to get keys pressed, mouse positions, and control default actions.