Nuxt 如何在数组上循环并使用 v-for 正确显示数据

问题描述 投票:0回答:1

我有一个电子商务网站,我想循环 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\"]",

感谢您的帮助。

json vue.js nuxt.js
1个回答
6
投票

拥有这种代码确实不太好。

<li v-for="(size, index) in sizes" :key="size.id">
  {{ 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="size.id">
  {{ size.name }}
</li>

拥有可变的

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

© www.soinside.com 2019 - 2024. All rights reserved.