user1525612
user1525612

Reputation: 1994

Vue v-for keys and values

I have the following JSON:

{
    "data": [
        {
            "title": "a title here",
            "news_url": "https://someurl",
            "sentiment": "Neutral",
            "type": "Article"
        },
        {
            "title": "a title here",
            "news_url": "https://someurl",
            "sentiment": "Negative",
            "type": "Article"
        },
        {
            "title": "a title here",
            "news_url": "https://someurl",
            "sentiment": "Neutral",
            "type": "Article"
        }
    ]
}

I have defined my data object 'news' like so:

data() {
   return {
     news: [],
  };
},

Now I am trying to v-for through these values so that I can get 3 divs each with the title value.

I am trying the following but I really don;t have much of a clue:

 <div v-for = "title in news">
     {{ title }}
</div>

I get the error: Elements in iteration expect to have 'v-bind:key' directives.

Any idea what I am doing wrong?

Thanks!

Upvotes: 0

Views: 6031

Answers (1)

Christian Carrillo
Christian Carrillo

Reputation: 2761

Vue documentation indicate:

It is recommended to provide a key attribute with v-for whenever possible, unless the iterated DOM content is simple, or you are intentionally relying on the default behavior for performance gains.

Since it’s a generic mechanism for Vue to identify nodes, the key also has other uses that are not specifically tied to v-for, as we will see later in the guide.

 

Don’t use non-primitive values like objects and arrays as v-for keys. Use string or numeric values instead.

Then you should use the key directive binding it with string or numeric value like this:

<div v-for = "(title, index) in news" :key="index">
     {{ title }}
</div>

Upvotes: 2

Related Questions