jsonvue.jsnuxt.js

How to loop on an array and display the data properly with a v-for?


I have an e-commerce site, I want to loop the nested data from json. I tried many things but couldn't find.

async fetch() {
    this.post = await fetch(
      `http://test.com/api.php?id=${this.$route.params.id}`
    ).then((res) => res.json())
  }

I use like this;

<h3>{{ post.title }}</h3>
<li v-for="(index, post.sizes) in sizes" :key="index">
        {{ sizes.index }}
      </li>

My json Data is : "sizes": "[\"XS\",\"S\",\"M\",\"L\"]",

thanks for helping.


Solution

  • Having this kind of code is not really okay.

    <li v-for="(size, index) in sizes" :key="size.id">
      {{ size }}
    </li>
    

    You need to update your data to something like this

    sizes: [
      { id: 1, name: "XS" },
      { id: 2, name: "S" },
      { id: 3, name: "M" },
      { id: 4, name: "L" },
    ]
    

    Or even better, fetch some ids from an API and then, use it like this

    <li v-for="size in sizes" :key="size.id">
      {{ size.name }}
    </li>
    

    Having a mutable index is not something that you should use for :key since it's does the opposite of what is is supposed to do.


    :key is essential, more info here: https://v2.vuejs.org/v2/style-guide/#Keyed-v-for-essential

    Here a blog article explaining this: https://michaelnthiessen.com/understanding-the-key-attribute#dont-use-an-index-as-the-key