Challenge: Track Mouse Position

Practice what we’ve learned about reusable composable.

Problem statement

Tracking users movements can be a useful way to create heat maps and determine how users are using your website. Your task is to create functionality to track the cursor’s position.

Challenge

You need to create a reusable composable called useMousePosition that tracks the current position of the cursor pointer. This composable should return a ref object with the cursor’s coordinates. You’ll need to add an event listener to listen for the mousemove. The useMousePosition composable should be used in the TrackMousePosition component to display the current position.

This exercise should be solved with Vue 3’s Composition API, and some additional requirements are that:

  • The state shouldn’t be created inside of the useMousePosition composable, but rather should be declared outside of it. It should be reused across all instances of the useMousePosition composable.
  • The event listener for tracking mouse movement should be initialized only once, no matter how many times the useMousePosition composable is used.

Get hands-on with 1200+ tech skills courses.