Vladimir Mujakovic
Vladimir Mujakovic

Reputation: 680

Trouble iterating over array using :v-for

I am attempting to iterate over a simple array using the v-for directive in my Nuxt.js App. Please see below.

<template>
    <nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top">
        <nuxt-link class="navbar-brand" to="/"> 
            <img class="image nav-logo" :src="logoSrc" alt="Logo" />
        </nuxt-link>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span></button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav" >
                <li :v-for="link in links" :key="link.label">
                    {{ link.label }}
                </li>
            </ul>
        </div>
    </nav>
</template>

<script>
    const linkArray = [
        {
            label: "Home",
            href: "/",
            class: ""
        },
        {
            label: "ABout",
            href: "/",
            class: ""
        },
        {
            label: "Our Menu",
            href: "/",
            class: ""
        },
        {
            label: "Contact Us",
            href: "/",
            class: "db-outline-cta"
        }
    ]

    export default {
        name: "Nav",
        data() {
            return {
                logoSrc: '/img/davidsbarlogo.png',
                links: linkArray
            }
        }
    }
</script>

As you can see, this is my component. I am going to be dynamically getting data for this component inside asyncData() later on when my cms is wired up, but I wanted to have some placeholder content.

I am repeatedly getting this error:

ERROR [Vue warn]: Error in render: "TypeError: Cannot read property 'label' of undefined" 00:00:49

I have tried with and wihtout the :key property, I know I should include one. I am fairly new to vue, if anyone has a recommendation I would be most grateful.

Upvotes: 0

Views: 197

Answers (2)

milmal
milmal

Reputation: 551

<ul class="navbar-nav">
  <li v-for="link in links" :key="link.label">{{link.label}}</li>
</ul>

Works like a charm https://codesandbox.io/s/recursing-kapitsa-rnr4h

Upvotes: 1

Tony
Tony

Reputation: 1432

Try this

<li v-for="(link, index) in links" :key="index">
  {{ link.label }}
</li>

However, using index as key isn't the best practice (as explained in this post) but since there's no truly unique id in your link object, this will do.

Upvotes: 1

Related Questions