2

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.

2
  • Hi, I think you need to use it like v-for="(index, size) in post.sizes" and then access {{ size }}. Also if this does not help then can you share the whole component how you are using it and also the whole jsonData structure. Commented Jun 19, 2021 at 10:19
  • 3
    I think your code should be something like this <li v-for="(size, index) in sizes" :key="index"> {{ size }}</li> Commented Jun 19, 2021 at 10:20

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.