You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用v-for循环数组并正确展示数据?电商网站嵌套JSON数据循环实现求助

Fixing Your Nested JSON Data Traversal Issue in Vue

Hey there! Let's break down why your v-for loop isn't working as expected—you've got two key issues to address, and fixing them will get those sizes displaying properly.

1. Your sizes data is a string, not an array

Looking at your JSON structure: "sizes": "[\"XS\",\"S\",\"M\",\"L\"]" — this is actually a stringified array, not a native JavaScript array that Vue can iterate over. When you fetch this data, Vue sees it as plain text, not a list of items.

To fix this, you need to parse the string into a real array using JSON.parse() after fetching the data:

async fetch() {
  const res = await fetch(`http://test.com/api.php?id=${this.$route.params.id}`);
  const fetchedData = await res.json();
  // Convert the stringified sizes into a proper array
  fetchedData.sizes = JSON.parse(fetchedData.sizes);
  this.post = fetchedData;
}

2. Your v-for syntax is incorrect

Your current loop has the order of arguments reversed, and variable naming is mixed up. The correct v-for syntax for iterating an array is (item, index) in array — where item is the current element, and index is its position (optional).

Update your template to this:

<h3>{{ post.title }}</h3>
<ul> <!-- Always wrap <li> elements in a <ul> for proper HTML structure -->
  <li v-for="(size, index) in post.sizes" :key="index">
    {{ size }}
  </li>
</ul>

Bonus Tip

If you have control over the backend API, it's better to return sizes as a native JSON array (like ["XS","S","M","L"]) instead of a stringified version. This eliminates the need for frontend parsing and reduces potential errors.

内容的提问来源于stack exchange,提问作者Anastasia Selezneva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 20:02:29