【问题标题】:Vue - deep nested object access Image on parentVue - 父级上的深层嵌套对象访问图像
【发布时间】:2021-02-20 07:18:18
【问题描述】:

我有 2 个 V-for 来渲染嵌套对象。在我的对象的第二层,我有一个图像,但我需要在我的第一个 V-for 上渲染该图像。

  <div v-for="(fruit, key) in fruits" :key="key">
        <div>
            <img :src="IWantRenderImageHereFrom2ndVfor" alt="" />
            <h1>{{ fruit }}</h1>
        </div>

        <div v-for="(piece, key) in fruit" :key="key">
            <h2>{{ key }}</h2>
        </div>
    </div>

这是我的对象的结构

   const fruits = {
    apple: {
        green: {
            image: image1,
            name: "green"
        },
        yellow: {
            image: image1,
            name: "yellow"
        }
    },
    mango: {
        red: {
            image: image2,
            name: "red"
        },
        pink: {
            image: image2,
            name: "pink"
        }
    }
};

每个 2 级对象都将具有我想在 1 级对象上渲染的相同图像。 我已经尝试抓取图像并在第一级创建一个新键,但是当循环渲染第二级时它会抛出一个错误

【问题讨论】:

  • 错误信息是什么?
  • @Tony 基本上是因为第二级对象的循环具有 Image 没有的键,例如 mango.red.name 它呈现,但 mango.image.name 不存在。我不知道循环时是否可以跳过图像属性编辑:我已经用名称键更新了对象以便更容易理解
  • fruits 的每个孙子都有一个image 键,那么您想要哪个子代?
  • @tony19 每个孙子都有相同的图像,所以我只想抓一个

标签: javascript loops vue.js object nested-object


【解决方案1】:

如果图像不是颜色对象独有的,则将其存储在那里没有意义,并且重复表明它不正确。您可以改用这样的结构,其中图像是第一级的属性:

const fruits = {
    apple: {
        image: "https://via.placeholder.com/200/333333",
        colors: ['green', 'yellow']
    },
    mango: {
        image: "https://via.placeholder.com/200/999999",
        colors: ['red', 'pink']
    },
};

您可以用一个简单的数组替换颜色对象。模板变为:

<div id="app">
  <div v-for="(fruit, key) in fruits" :key="key">
    <div>
      <img :src="fruit.image" alt="" />
      <h1>{{ key }}</h1>
    </div>

    <div v-for="color in fruit.colors" :key="color">
      <h2>{{ color }}</h2>
    </div>
  </div>
</div>

这是一个演示:

const fruits = {
    apple: {
        image: "https://via.placeholder.com/200/333333",
        colors: ['green', 'yellow']
    },
    mango: {
        image: "https://via.placeholder.com/200/999999/FFFFFF",
        colors: ['red', 'pink']
    },
};

new Vue({
  el: "#app",
  data() {
    return {
      fruits
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div v-for="(fruit, key) in fruits" :key="key">
    <div>
      <img :src="fruit.image" alt="" />
      <h1>{{ key }}</h1>
    </div>

    <div v-for="color in fruit.colors" :key="color">
      <h2>{{ color }}</h2>
    </div>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 2021-07-04
    • 2020-12-15
    • 2015-07-19
    • 1970-01-01
    • 2022-11-04
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    相关资源
    最近更新 更多