2

我正在尝试将此数据传递给 vue 中的组件。我可以在子组件中获取数据,并且可以渲染数组,或者通过调用访问每个对象的属性products[0].name,但我希望在v-for循环中分别渲染每个对象。请帮忙!!

父组件:

<template>
  <div>
    <h1>Welcome To Our Shop</h1>
    <div class="products">
      <div v-for="product in products" v-bind:key="product.name">
        <div><ShopItem v-bind:products="products" /></div>
      </div>
    </div>
  </div>
</template>

<script>
import ShopItem from "../components/Shop/ShopItem";
export default {
  name: "Shop",
  components: { ShopItem },
  data() {
    return {
      products: [
        {
          name: "Basic Deck",
          price: 7,
          description:
            "The Basic Deck includes 68 cards: 10 cards in each of six categories, three icon legend cards, five blank cards for developing your own backstory elements, and instructions.",
          image: require("@/assets/Draeorc.png"),
        },
        {
          name: "Card Bundle",
          price: 10,
          description:
            "The Card Bundle includes the Basic Deck, Technical Booster, Mystical Booster and instructions as a single self-printable PDF.",
          image: require("@/assets/Twilight.png"),
        },
        {
          name: "Full Bundle with Box",
          price: 12,
          description:
            "The Full Bundle includes the Basic Deck, Technical Booster, Mystical Booster, instructions and tuck box as a single self-printable PDF.",
          image: require("@/assets/Orig_Godbringer.png"),
        },
      ],
    };
  },
};
</script>

子组件:

<template>
  <div class="product-container">
    <div>
      <h2>{{ products[0].name }}</h2> //this is where I want to call on the name
      <div class="card-container">
        <img src="../../assets/Draeorc.png" alt="cards" />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "ShopItem",
  props: ["products"],
};
</script>

4

2 回答 2

2

这里

  <div v-for="product in products" v-bind:key="product.name">
    <div><ShopItem v-bind:products="products" /></div>
  </div>

你的代码没有意义为什么?

因为你想通过这里是 products 的数组并显示 products 数组中的每个项目。当您遍历数组时,适合该迭代的项目将被传递给 ShopItem组件,无需使用访问索引
products[index]

所以最好执行以下操作

<div><ShopItem v-bind:product="product" /></div>

因此,您的组件在通过循环ShopItem时将可以访问产品之一v-for

于 2020-07-09T23:13:44.650 回答
1

改变

v-bind:products="products"

v-bind:products="product"

因为您使用的是 for-of 循​​环

在子组件上,更改:

products[0].name

products.name

并且由于该属性是一个对象,而不是数组,因此最好将您的属性名称更改productproducts

所以你将在父组件上有这个:

<div v-for="product in products" v-bind:key="product.name">
    <div><ShopItem :product="product" /></div>
    // :product is a shorthand for v-bind:product
</div>

这在子组件上:

<template>
  <div class="product-container">
    <div>
      <h2>{{ product.name }}</h2> //this is where I want to call on the name
      <div class="card-container">
        <img src="../../assets/Draeorc.png" alt="cards" />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "ShopItem",
  props: ["product"],
};
</script>
于 2020-07-09T23:12:18.443 回答