0
0
Vueframework~15 mins

Accessing the native event object in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Accessing the native event object
📖 Scenario: You are building a simple Vue 3 app where a button click shows the exact mouse coordinates of the click event.
🎯 Goal: Create a Vue 3 component that captures the native click event on a button and displays the clientX and clientY coordinates of the mouse click.
📋 What You'll Learn
Use Vue 3 Composition API with <script setup>
Create a reactive variable to store the click coordinates
Add a button with a click event listener that accesses the native event object
Display the clientX and clientY values on the page
💡 Why This Matters
🌍 Real World
Capturing native event details like mouse position is common in interactive web apps such as drawing tools, games, or custom UI controls.
💼 Career
Understanding how to access native event objects and use reactive state is essential for frontend developers working with Vue or similar frameworks.
Progress0 / 4 steps
1
Set up reactive variables for coordinates
In the <script setup> block, import ref from 'vue' and create two reactive variables called clickX and clickY initialized to 0.
Vue
Need a hint?

Use import { ref } from 'vue' and then const clickX = ref(0) and const clickY = ref(0).

2
Add click event handler function
Below the reactive variables, create a function called handleClick that takes a parameter event. Inside the function, set clickX.value to event.clientX and clickY.value to event.clientY.
Vue
Need a hint?

Define function handleClick(event) and update clickX.value and clickY.value using event.clientX and event.clientY.

3
Bind the click event to the button
In the <template>, add a @click event listener to the <button> that calls the handleClick function and passes the native event object.
Vue
Need a hint?

Add @click="handleClick" to the <button> tag.

4
Add accessibility and finalize display
Add an aria-label attribute to the <button> with the value Click to get mouse coordinates. Also, ensure the coordinates are displayed inside a <p> tag with a clear label.
Vue
Need a hint?

Add aria-label="Click to get mouse coordinates" to the <button> tag for accessibility.