2

我开始学习 vue,我试图练习一点,但我被 for 循环卡住了。

我正在调用我为更好地理解数据处理而开发的 api。调用的输出是:

[
    {
        "_id": "ID1",
        "customerID": "ASDF",
        "purchases": [
            {
                "laptop": "DELL",
                "price": "500"
            },
            {
                "monitor": "DELL",
                "price": "200"
            }
        ]
    },
    {
        "_id": "ID2",
        "customerID": "FDSA",
        "purchases": [
            {
                "laptop": "MacBook",
                "price": "1800"
            },
            {
                "monitor": "DELL",
                "price": "300"
            }
        ]
    }
]

我的目的是使用 v-for 来遍历购买数组,以便它可以显示 json 中每个条目的数组内容。

我正在使用的 vue 模板是:

<template>
  <div>
    <div class="card" v-for="data in purchases" :key="data.purchases">
        <div class="card-image">
          <div class="card-content">
            <div class="media">
              <div class="media-content">
                <p class="title is-4">PURCHASES</p>
                <div
                  class="columns is-variable is-1-mobile is-0-tablet is-3-desktop is-8-widescreen is-2-fullhd"
                >
                  <div class="column">Laptop: {{data.purchases[0].laptop}}</div>
                  <div class="column">Monitor: {{data.purchases[0].monitor}}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
    </div>
  </div>
</template>

vue文件中的脚本:

<script>
import { ref } from "@vue/composition-api";

export default {
  setup() {
    const purchases = ref([]);
    const API_url = "http://localhost:8383/purchases";

    async function getData() {
      const reponse = await fetch(API_url);
      const json = await reponse.json();
      purchases.value = json;
      console.log(purchases);
    }

    getData();

    return {
      purchases,
    };
  },
};
</script>

我知道我只显示了数组的第一个元素,而这正是我的问题,如何使用 v-for 遍历整个数组。

我将非常感谢您的帮助:)

4

1 回答 1

1

创建另一个嵌套v-for循环data.purchases

<template>
  <div>
    <div class="card" v-for="data in purchases" :key="data.purchases">
        <div class="card-image">
          <div class="card-content">
            <div class="media">
              <div class="media-content">
                <p class="title is-4">PURCHASES</p>
                <div
                  class="columns is-variable is-1-mobile is-0-tablet is-3-desktop is-8-widescreen is-2-fullhd"
                >
                <template v-for="purchase  in data.purchases">
                  <div class="column">Laptop: {{purchase.laptop}}</div>
                  <div class="column">Monitor: {{purchase.monitor}}</div>
               </template>
                </div>
              </div>
            </div>
          </div>
        </div>
    </div>
  </div>
</template>
于 2020-08-23T09:44:20.300 回答