Vue - 深层嵌套对象访问父图像

Vue - deep nested object access Image on parent

我有 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"
        }
    }
};

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

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

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>