【问题标题】:TypeError: Cannot read properties of undefined (reading 'products')TypeError:无法读取未定义的属性(读取“产品”)
【发布时间】:2021-12-25 17:32:13
【问题描述】:

我正在尝试获取产品,然后检查产​​品 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.js nuxt.js


    【解决方案1】:

    问题出在这一行:

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

    阅读更具体:data.products

    你看,computed 属性 bestsellers 在你的 axios 调用完成之前被评估。

    因此,Vue 在data 中找不到products,因为您的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 []
    }
    

    【讨论】:

    • 谢谢,它仍然在做。我已经在 axios 调用中将其更改为您所说的内容,然后计算的过滤器现在是 et 关键字 = this.products.product.filter(prod.... 我得到 'TypeError: Cannot read properties of undefined (reading 'filter') '
    • 那是因为产品是undefined。尝试添加if 语句。我已经更新了我的答案。或者,如果您只使用该属性,则将 response.data.products.product 分配给 this.products。祝你好运?
    • 好萌,谢谢。知道为什么 facebook 应用程序不返回任何产品吗?这似乎只是产品的问题,其他数据还可以,但其他数据来自后端无头 cms,而产品数据来自 json 文件。它都是同一个域,所以不应该是 CORS 问题...
    • @jord49 抱歉,没有。我从未尝试过他们的 API ?‍♂️
    猜你喜欢
    • 1970-01-01
    • 2020-11-23
    • 2021-11-26
    • 2021-11-24
    • 2021-12-20
    • 2021-11-27
    • 2022-01-21
    • 2021-12-04
    • 2021-12-09
    相关资源
    最近更新 更多