Ana*_*eva 2 json vue.js nuxt.js
我有一个电子商务网站,我想循环 json 中的嵌套数据。我尝试了很多东西但找不到。
async fetch() {
this.post = await fetch(
`http://test.com/api.php?id=${this.$route.params.id}`
).then((res) => res.json())
}
Run Code Online (Sandbox Code Playgroud)
我这样使用;
<h3>{{ post.title }}</h3>
<li v-for="(index, post.sizes) in sizes" :key="index">
{{ sizes.index }}
</li>
Run Code Online (Sandbox Code Playgroud)
我的 json 数据是:"sizes": "[\"XS\",\"S\",\"M\",\"L\"]",
感谢您的帮助。
拥有这种代码确实不太好。
<li v-for="(size, index) in sizes" :key="index">
{{ size }}
</li>
Run Code Online (Sandbox Code Playgroud)
您需要将数据更新为类似这样的内容
sizes: [
{ id: 1, name: "XS" },
{ id: 2, name: "S" },
{ id: 3, name: "M" },
{ id: 4, name: "L" },
]
Run Code Online (Sandbox Code Playgroud)
或者更好的是,从 API 中获取一些 id,然后像这样使用它
<li v-for="size in sizes" :key="side.id">
{{ size.name }}
</li>
Run Code Online (Sandbox Code Playgroud)
拥有可变的index东西不是你应该使用的,:key因为它的作用与应该做的相反。
:key至关重要,更多信息请参见:https ://v2.vuejs.org/v2/style-guide/#Keyed-v-for-essential
这里有一篇博客文章解释了这一点: https: //michaelnthiessen.com/understanding-the-key-attribute#dont-use-an-index-as-the-key
| 归档时间: |
|
| 查看次数: |
4798 次 |
| 最近记录: |