Within a Vue component, there exists a menu structured as follows:
<ul class="menu-outer-wrapper">
<li><a href="/foo-1">Foo 1</a></li>
<li class="has-children">
<a href="/foo-2">Foo 2</a>
<ul>
<li><a href="/child-1">Child 1</a></li>
<li><a href="/child-2">Child 2</a></li>
<li><a href="/child-3">Child 3</a></li>
</ul>
</li>
<li><a href="/foo-5">Foo 5</a></li>
<li class="has-children">
<a href="/foo-6">Foo 6</a>
<ul>
<li><a href="/child-1">Child 1</a></li>
<li><a href="/child-2">Child 2</a></li>
</ul>
</li>
<li><a href="/foo-7">Foo 7</a></li>
<li><a href="/foo-8">Foo 8</a></li>
</ul>
The objective is to apply the hovered
class to li.has-children
elements when hovered over (mouseenter
) in order to facilitate smoother animations for the children within that dropdown. The class should be removed upon mouseleave
.
Although CSS can achieve this, controlling delays and fade-ins becomes complex without adding classes.
A possible approach involves the below code implementation:
...
mounted(){
let liWithChildren = document.querySelectorAll( '.menu-outer-wrapper > li.has-children' );
liWithChildren.forEach((event) => {
// Code to add class to hovered element
});
}
Is this considered best practice? Can it be implemented without using data
, given that the menu is dynamically generated via a CMS?
Update 1
An effort is made to maintain readability by avoiding approaches like:
<ul class="menu-outer-wrapper">
<li :class="[ { 'hovered' : someVar } ]">
<a href="/foo-1">Foo 1</a>
</li>
<li :class="[ { 'hovered' : someVar }, 'has-children' ]">
<a href="/foo-2">Foo 2</a>
<ul>
<li><a href="/child-1">Child 1</a></li>
<li><a href="/child-2">Child 2</a></li>
<li><a href="/child-3">Child 3</a></li>
</ul>
</li>
<li :class="[ { 'hovered' : someVar } ]">
<a href="/foo-3">Foo 2</a>
</li>
...
...
...
This method does not align with the dynamically generated menu and introduces unnecessary complexity to the markdown.
Update 2
To simplify comprehension, the example was condensed. However, due to feedback, further insight regarding the dynamically generated menu is addressed:
<nav id="secondary-menu" v-if="secondaryMenu">
<ul>
<li
:class="[ { 'has-children': r.children } ]"
v-for="(r, r_key, r_index) in secondaryMenu">
<a :href="r.url" :title="r.title">
{{ r.title }}
</a>
<ul class="children" v-if="r.children">
<li v-for="(c1, c1_key, c1_index) in r.children">
<a :href="c1.url" :title="c1.title">
{{ c1.title }}
</a>
</li>
</ul>
</li>
</ul>
</nav>