Vue Tip: Detect Mouse Hover
You can use Vue event handlers to detect mouse hover events. To keep track of the hover status of an element, you need to keep track of when the mouse enters the element, and when the mouse leaves the element.
Event Handlers
We can use the mouseleave event to keep track of when the mouse leaves the element.
To detect when the mouse enters the element you can use two events:
The mouseover
event is triggered on an element and every single one of its ancestor elements in the DOM tree (i.e. it bubbles) which could cause serious performance problems in deep hierarchies. mouseenter
doesn’t bubble so we can use it without worrying about this.
Try it yourself in this interactive demo:
Vue Component
Let's hook everything up and look at a Vue component that detects mouse hover events:
The reactive property isHovered
indicates if the mouse is hovering over the element or not.
You can now use this reactive variable to show/hide elements when a certain element is hovered or toggle CSS classes.
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Nuxt Tip: Add Custom iframe Tab to Nuxt DevTools
Nuxt DevTools is designed to be extensible. You can add your own modules' integration to the DevTools.
Vue Tip: Don't Use v-if With v-for
It can be tempting to combine v-if with v-for but you should avoid it as it will throw an error.