Skip to content
Advertisement

Add class to element on hover in Vue, without using data

In a Vue-component, I have a menu like this:

JavaScript

And I would like to add the class hovered to the li.has-children-elements upon hover (mouseenter) (to be able to make some nicer animations for the children of that dropdown. And remove that class on mouseleave.

I know that there are options to do this with pure CSS, – but controlling delays and soft fade-in’s are a pain (and become very messy very fast, without adding some classes).

I imagined doing something like this:

JavaScript

But is that the way to go? And can I do it without using data (since the menu is dynamically generated by a CMS-system.


Update 1

I’m trying to keep my markdown readable. So I would like to avoid something like this:

JavaScript

Both since it won’t gel with the dynamically generated menu. And also since it add a lot of noise to the markdown.


Update 2

I simplified the example, to make it easier to digest. But due to the comments I figured I would elaborate on the dynamic generated menu. I’m making it something like this:

JavaScript

Advertisement

Answer

You just need the @mouseenter and @mouseleave events. All you need to do is listen for the appropriate events on all list-items that could have children, then perform your class addition (or removal) if the target element has the class of “has-children”. Here’s how I would do it:

JavaScript

Here’s a very unaesthetic sandbox of this in action. Let me know if this works for you 🙂

https://codesandbox.io/s/headless-brook-ysq97?file=/src/components/HoverNav.vue:0-1169

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement