我已经初始化了数据。
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实例显示预期结果
但是如果我在模板中调用 {{ 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/