There are plenty of ways to access the cursor position if you ever need it in your Vue app. Using the VueUse library’s useMouse functionality is probably one of the easiest ways. However, I find that overkill for this simple functionality. Let’s have a look at how we can achieve it using vanilla JavaScript.
Here’s the code we’d need to achieve the same:
<template>
<div id="app">
<h2>Mouse position:</h2>
<p>Mouse position X: {{ mousePosX }}</p>
<p>Mouse position Y: {{ mousePosY }}</p>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
mousePosX: 0,
mousePosY: 0,
};
},
mounted() {
document.addEventListener("mousemove", (event) => {
this.mousePosX = event.clientX;
this.mousePosY = event.clientY;
});
},
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #000000;
margin: 60px;
}
</style>
Code language: HTML, XML (xml)
In the above code, we’ve added an event listener mousemove on line 19. We’ve added it to the document object. We then declared two reactive states named mousePosX and mousePosY. Next, we updated these states from inside the event listener whenever there’s a mousemove event fired. We’ve then displayed the mousePosX and mousePosY values using the template on lines 4 and 5.