我已经初始化了数据。
data () {
return {
current_product: {},
current_ID: '',
}
}
Run Code Online (Sandbox Code Playgroud)
然后,我从生命周期创建挂钩上的 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)
})
}
Run Code Online (Sandbox Code Playgroud)
最后,我使用计算属性来获取一些值
// 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
}
Run Code Online (Sandbox Code Playgroud)
vue 实例显示预期结果
但是如果我调用{{ focusedProduct_SKUS_NoDupSizes }}
模板。
Error in render: "TypeError: Cannot read property 'filter' of undefined"
怎么了?我的第一个猜测是computed property
使用它的初始结构current_product
是{} empty object
. 但这不就是如何初始化一个对象吗?
因为:
computed:
// ...
focusedProduct_SKUS_NoDupSizes () {
var newArr = this.current_product.product_SKU.filter((sku, index, self) =>
^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
您应该product_SKU
使用空数组进行初始化:
data () {
return {
current_product: {product_SKU: []}, // changed here
current_ID: '',
}
}
Run Code Online (Sandbox Code Playgroud)
这是必需的,因为计算属性将立即执行,甚至在您的 Ajax 有机会返回之前。
将其声明为空,以便计算不会引发错误。当 Ajax 完成时,它会自动重新计算。
即使 Ajax 开始于created()
,它也不会在第一次执行计算之前返回。更多详情请点击此处。
归档时间: |
|
查看次数: |
8832 次 |
最近记录: |