首页 > 解决方案 > 无法获取计算属性(数组)

问题描述

试图将 ' displayImages' 数组作为计算属性。使用默认的“ selected”属性 = 0。this.selected 在 mouseover 和 click 事件上相应改变。

当试图得到计算的 ' displayImages' 它说:

"this.variations[this.selected] is undefined."

我正在使用 api 来获取我的产品数据和图像。

<template>
  <div id="product-page">
    <v-card width="100%" class="product-card">
      <div class="image-carousel">
        <v-carousel height="100%" continuos hide-delimiters>
          <v-carousel-item
            v-for="(image, i) in displayImages"
            :key="i"
            :src="image"
          >
          </v-carousel-item>
        </v-carousel>
      </div>
      <div class="details">
        <h2>{{ this.title }}<br />Price: ${{ this.price }}</h2>
        <p>{{ this.details }}</p>
        <ul style="list-style: none; padding: 0">
          <li
            style="border: 1px solid red; width: auto"
            v-for="(color, index) in variations"
            :key="index"
            @mouseover="updateProduct(index)"
            @click="updateProduct(index)"
          >
            {{ color.color }}
          </li>
        </ul>
        <div class="buttons">
          <v-btn outlined rounded
            >ADD TO CART<v-icon right>mdi-cart-plus</v-icon></v-btn
          >
          <router-link to="/shop">
            <v-btn text outlined rounded> BACK TO SHOP</v-btn>
          </router-link>
        </div>
      </div>
    </v-card>
  </div>
</template>

<script>
export default {
  name: "Product",
  props: ["APIurl"],
  data: () => ({
    title: "",
    details: "",
    price: "",
    variations: [],
    selected: 0,
  }),
  created() {
    fetch(this.APIurl + "/products/" + this.$route.params.id)
      .then((response) => response.json())
      .then((data) => {
        //console.log(data);
        this.title = data.title;
        this.details = data.details.toLowerCase();
        this.price = data.price;
        data.variations.forEach((element) => {
          let imagesArray = element.photos.map(
            (image) => this.APIurl + image.url
          );
          this.variations.push({
            color: element.title,
            images: imagesArray,
            qty: element.qty,
            productId: element.productId,
          });
        });
      });
  },
  computed: {
    displayImages() {
      return this.variations[this.selected].images;
    },
  },
  methods: {
    updateProduct: function (index) {
      this.selected = index;
      console.log(index);
    }
  },
};
</script>

标签: vue.js

解决方案


为了避免这种错误,您必须使用安全导航属性。

请记住,它仅在应用程序加载时很有用。

尝试这样的事情:

<script>
export default {
  name: 'Product',
  computed: {
    displayImages() {
      if (this.variations[this.selected]) {
        return this.variations[this.selected].images;
      }
      return [];
    },
  },
};
</script>


推荐阅读