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

