我有一个电子商务网站,我想从 json 循环嵌套数据。我尝试了很多东西,但找不到。
async fetch() {
this.post = await fetch(
`http://test.com/api.php?id=${this.$route.params.id}`
).then((res) => res.json())
}
我是这样用的;
<h3>{{ post.title }}</h3>
<li v-for="(index, post.sizes) in sizes" :key="index">
{{ sizes.index }}
</li>
我的 json 数据是:"sizes": "[\"XS\",\"S\",\"M\",\"L\"]",
感谢您的帮助。
答案 0 :(得分:1)
拥有这种代码并不好。
<li v-for="(size, index) in sizes" :key="index">
{{ size }}
</li>
您需要将数据更新为这样的内容
sizes: [
{ id: 1, name: "XS" },
{ id: 2, name: "S" },
{ id: 3, name: "M" },
{ id: 4, name: "L" },
]
或者更好的是,从 API 中获取一些 id,然后像这样使用它
<li v-for="size in sizes" :key="side.id">
{{ size.name }}
</li>
拥有可变的 index
不是您应该用于 :key
的东西,因为它的作用与应该做的相反。
:key
是必不可少的,更多信息在这里:https://vuejs.org/v2/style-guide/#Keyed-v-for-essential
这里有一篇博客文章解释了这一点:https://michaelnthiessen.com/understanding-the-key-attribute#dont-use-an-index-as-the-key