Answer the question
In order to leave comments, you need to log in
How to assign active class to links in recursive menu in Vue.js?
Faced such task as the recursive menu. It turned out to implement the menu itself - when the links are clicked, an active class is assigned and nested items are opened - I'm stuck on how to assign an active class to links in nested components.
Calling the Categories component in the template:
<div id="app">
<categories :categories="{{ $categories }}"></categories>
</div>
<template>
<aside class="menu">
<ul class="menu-list">
<category
v-for="(category, index) in categories"
:key="index"
:id="category.id"
:label="category.name"
:nodes="category.children"
:is-active="activeItem == category.id"
@toggled="onToggle"
>
</category>
</ul>
</aside>
</template>
<script>
import Category from './Category.vue'
export default{
props:['categories'],
data(){
return {
activeItem: null
}
},
components: { Category },
methods:{
onToggle(index){
this.activeItem = index;
}
}
}
</script>
<template>
<li>
<a href="#" v-text="label" @click="toggleChildren" :class="{'is-active': isActive}"></a>
<ul>
<category
v-if="showChildren"
v-for="(node, index) in nodes"
:key="index"
:nodes="node.children"
:label="node.name"
:id="node.id"
>
</category>
</ul>
</li>
</template>
<script>
export default {
props: [ 'label', 'nodes', 'id', 'isActive'],
data() {
return {
showChildren: false
}
},
name: 'category',
methods: {
toggleChildren() {
this.showChildren = !this.showChildren;
this.$emit('toggled', this.id);
}
}
}
</script>
Answer the question
In order to leave comments, you need to log in
In the category component, you forgot to subscribe to the toggled event generated by child categories (it should be passed to the parent). And instead of isActive (you also forgot about it when creating child categories for some reason), it is probably worth passing the id of the element - otherwise it is not clear who and at what level of nesting should be considered active.
Well, in general - why two components to build a nested menu? Somehow it gets complicated. One is enough. For example .
Damn, what a hell of a heap of if / else, make a jump table already. And where is your foreach that doesn't work? Are you suggesting that we look for it ourselves and guess whether this is the foreach? If you want to get an answer to a question, take the trouble to facilitate the work of those who will answer.
AAAAA!!!!! Urgently write a letter of resignation, well, you can’t do it, Lord !!!
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question