·
1 min read

Vue Tip: Detect Mouse Hover

Vue Tip: Detect Mouse Hover Image

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.

mouseenter vs. mouseover event

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:

Component.vue
<script setup> import { ref } from 'vue' const isHovered = ref(false) </script> <template> {{ isHovered }} <div @mouseenter="isHovered = true" @mouseleave="isHovered = false" /> </template>

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:

I will never share any of your personal data. You can unsubscribe at any time.