Home » vue » How to v-for loop a nested navigation in Vue.js?

How to v-for loop a nested navigation in Vue.js?

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’m trying to set up a multi-level navigation using Vue.js.

When I try to use v-for inside my v-for in the parent navigation element, Vue throws an error and says item is undefined.

HTML:

<nav id="hf-nav">
  <a v-for="item in itemLinks" :href="`${item.link}`"></a>
    {{ item.title }}
    <nav v-if="item.subItems">
      <a v-for="sub in item.subItems" :href="`${sub.link}`">{{ sub.title }}</a>
    </nav>
  </a>
</nav>

JavaScript:

new Vue({
  el: '#hf-main',
  data: {
    homepage: true,
    itemLinks: [
      { title: 'Home', link: './' },
      {
        title: 'Diensten',
        link: './diensten',
        subItems: [
          { title: 'Elektromontage', link: './elektromontage' },
          { title: 'Installatietechniek', link: './installatietechniek' },
          { title: 'Schoonmaak', link: './schoonmaak' },
          { title: 'Overige diensten', link: './overige-diensten' },
        ],
      },
      { title: 'Over H&F', link: './over-hf' },
      { title: 'Contact', link: './contact' },
    ],
  },
})

I want Vue to loop and check if there’s a second level in the inside an itemLinks object, and if so I want Vue to execute another loop.

Answers:

The problem is the closing </a> tag at the end of this line:

<a v-for="item in itemLinks" :href="`${item.link}`">{{ item.title }}</a>

The item for the v-for will only be defined within the scope of this tag, so the lines that follows won’t know anything about it.

My guess would be that you were aiming for this:

<nav id="hf-nav">
    <template v-for="item in itemLinks">
        <a :href="`${item.link}`">{{ item.title }}</a>
        <nav v-if="item.subItems">
            <a v-for="sub in item.subItems" :href="`${sub.link}`">{{ sub.title }}</a>
        </nav>
    </template>
</nav>

I’m a little surprised that your editor wasn’t warning you that the HTML tags weren’t balanced. The closing </a> tag on the penultimate line of your code doesn’t have a matching opening tag.

Incidentally, there’s no need to use backticks for :href="`${item.link}`", you can just write :href="item.link". Likewise for :href="sub.link".