0

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!

user1525612
  • 1,864
  • 1
  • 21
  • 33
  • 1
    I guess u don't have id in news array.. Add index
    {{ title }}
    You can refer this link for more usage of index - https://stackoverflow.com/questions/44531510/why-not-always-use-the-index-as-the-key-in-a-vue-js-for-loop
    – Viresh Mathad Sep 15 '19 at 18:27
  • Vue requires :key https://vuejs.org/v2/guide/list.html#Maintaining-State – doubleui Sep 15 '19 at 18:30
  • Thanks Viresh. I have tried your solution here: https://jsfiddle.net/Lf69b8vq/1/ Something is happening but it prints out the numbers 1,2,3 instead of the titles. – user1525612 Sep 15 '19 at 18:45
  • Thanks, It works now when do {{ index.title }} instead of {{ title }} - https://jsfiddle.net/de0xhap6/ – user1525612 Sep 15 '19 at 18:51

1 Answers1

2

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>
tony19
  • 125,647
  • 18
  • 229
  • 307
Christian Carrillo
  • 2,751
  • 2
  • 9
  • 15