Solution: Track Mouse Position
Here’s the solution of how to create a reusable composable to track mouse position.
We'll cover the following
Solution
Your task was to create the useMousePosition
composable and use it in the App.vue
component. Here are the required changes:
For the src/composables/useMousePosition.js
file:
- Import the
reactive
andtoRefs
methods from thevue
package. - Create a reactive
mousePosition
object withx
andy
values set to0
using thereactive
method. - Add an event listener for the
mousemove
event. The callback should extractclientX
andclientY
values from the event object passed as an argument. These values should be used to update themousePosition
object. - Return a
useMousePosition
function that returnstoRefs(mousePosition)
.
For the src/App.vue
file:
- Import the
useMousePosition
composable and return its result in thesetup
method. - Update the template to render
x
andy
values that are returned by theuseMousePosition
composables.
Get hands-on with 1400+ tech skills courses.