vue.js - 为什么 "Error in render: TypeError: Cannot read property ' 过滤器' of undefined' 甚至返回已经可用的数据?

标签 vue.js

我已经初始化了数据。

data () {
  return {
    current_product: {},
    current_ID: '',
  }
}

然后,我在生命周期 created Hook 上从 REST API 获取数据。

created () {
  var skuID = this.$store.state.selected_productSKU.productSKU_ID

  axios.get(`http://localhost:8081/api/products/${skuID}`)
    .then(response => {
      this.current_ID = response.data.product_ID
      this.current_product = response.data
    })
    .catch(e => {
      alert(e)
  })
}

最后,我使用计算属性来获取一些值

// THIS JUST RETURN ['XL', 'M']
focusedProduct_SKUS_NoDupSizes () {
  var newArr = this.current_product.product_SKU.filter((sku, index, self) =>
    index === self.findIndex(t => (
      t.productSKU_size === sku.productSKU_size
    ))
  )
  var x = newArr.map(a => a.productSKU_size)
  return x
}

vue实例显示预期结果

Expected Result

但是如果我在模板中调用 {{ focusedProduct_SKUS_NoDupSizes }}

  • 它没有呈现。
  • 浏览器返回错误渲染错误:“TypeError: Cannot read property 'filter' of undefined”

发生了什么事?我的第一个猜测是 computed property 使用 current_product 的初始结构,它是 {} 空对象。但这不就是如何初始化一个对象吗?

最佳答案

因为:

computed:
  // ...
  focusedProduct_SKUS_NoDupSizes () {
    var newArr = this.current_product.product_SKU.filter((sku, index, self) =>
                                      ^^^^^^^^^^^

您应该使用空数组初始化 product_SKU:

data () {
  return {
    current_product: {product_SKU: []}, // changed here
    current_ID: '',
  }
}

这是必需的,因为计算属性将立即执行,甚至在您的 Ajax 有机会返回之前。

将其声明为空,这样计算就不会抛出错误。当 Ajax 执行时,它会自动重新计算。

即使 Ajax 在 created() 处启动,它也不会在 第一次执行计算之前返回。 More details about this here .

关于vue.js - 为什么 "Error in render: TypeError: Cannot read property ' 过滤器' of undefined' 甚至返回已经可用的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49663539/

相关文章:

javascript - Vue - 为什么有些图像在生产中获得哈希值,而其他图像则没有?

注销后在请求方法中添加 Django/Vue 大括号

excel - 如何使用 laravel 和 vuejs 下载文件

javascript - Vuejs 拼接重复

javascript - 动态创建的输入。无法使用 $refs 那么如何获取例如重点?

vue.js - 将 shell 输出流式传输到 Web 前端

vue.js - NuxtServerInit 无法在 Vuex 模块模式下工作 - Nuxt.js

vue.js - 如何使用 prop 控制子组件对父组件的可见性?

JavaScript/VueJS : Check if an Array contains an object with an element that has specific value

typescript - 如何在VueJS 3.0 中使用defineComponent 注册本地组件