首页 > 解决方案 > TypeError:无法读取未定义的属性(读取“产品”)

问题描述

我正在尝试获取产品,然后检查产​​品 pId 是否在数组中,如果是则过滤。当我软刷新“TypeError:无法读取未定义的属性”(读取“产品”)时出现错误,几乎就像当计算试图获取数据时我的“this.products”尚未填充一样。尝试添加一些 if 语句来检查数据,但没有运气。

<script>
export default {
  data() {
    return {
      popular_products: [],
      products: [],
    }
  },

  computed: {
    bestsellers() {
      const keywords = this.popular_products
      let array = []
      for (var index = 0; index < keywords.length; index++) {
        const keyword = this.products.data.products.product.filter(
          (product) => product.pId == keywords[index].ProductNumber
        )
        array = array.concat(keyword)
      }
      return array
    },
  },

  mounted() {
    axios
      .get(
        'https://myurl/admin/api/collections/get/popularproducts?token=account-9306f9192049d3c442e565f2de5372'
      )
      .then((response) => (this.popular_products = response.data.entries))

    axios
      .get('https://myurl/products.json')
      .then((response) => (this.products = response))
  },
}
</script>

标签: vue.jsnuxt.js

解决方案


问题在于这一行:

let keyword = this.products.data.products.product.filter(product => product.pId == keywords[index].ProductNumber);

更具体的阅读:data.products

您会看到,在您的呼叫完成之前评估computed属性。bestsellersaxios

因此,Vue 无法找到productsdata因为您this.products没有data密钥。

最好的解决方案是更改此分配:

- .then(response => (this.products = response)); // delete this line
+ .then(response => (this.products = response.data.products)); // add this line

评论后更新

if (this.products.product) {
  return this.products.product.filter(...)
} else {
  return []
}

推荐阅读