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 and toRefs methods from the vue package.
  • Create a reactive mousePosition object with x and y values set to 0 using the reactive method.
  • Add an event listener for the mousemove event. The callback should extract clientX and clientY values from the event object passed as an argument. These values should be used to update the mousePosition object.
  • Return a useMousePosition function that returns toRefs(mousePosition).

For the src/App.vue file:

  • Import the useMousePosition composable and return its result in the setup method.
  • Update the template to render x and y values that are returned by the useMousePosition composables.

Get hands-on with 1200+ tech skills courses.