Javascript NUXT-如何更好地重构计算属性
我有一个NUXT项目,我有的数据有时不存在。 然而,计算的属性越来越长,我觉得出于某种原因,这不是最佳实践。有没有一种方法可以缩短这个时间,或者在不破坏站点(如果站点不存在)的情况下,通过传入参数使计算属性动态化Javascript NUXT-如何更好地重构计算属性,javascript,object,nuxt.js,Javascript,Object,Nuxt.js,我有一个NUXT项目,我有的数据有时不存在。 然而,计算的属性越来越长,我觉得出于某种原因,这不是最佳实践。有没有一种方法可以缩短这个时间,或者在不破坏站点(如果站点不存在)的情况下,通过传入参数使计算属性动态化 export default { props: { halfWidth: { type: Boolean, default: false }, slice: { type: Object, default: (
export default {
props: {
halfWidth: {
type: Boolean,
default: false
},
slice: {
type: Object,
default: () => {}
}
},
computed: {
title() {
return this.slice?.data?.shopifyproduct?.title
},
price() {
return this.slice?.data?.shopifyproduct?.variants[0]?.price
},
image() {
return this.slice?.data?.shopifyproduct?.image?.src
},
alt() {
return this.slice?.data?.shopifyproduct?.image?.alt
},
desc() {
return this.slice?.data?.short_description[0]?.text
},
handle() {
return this.slice?.data?.shopifyproduct?.handle
}
}
}
</script>
由于您的大多数计算属性都依赖于shopifyProduct,因此您可以创建一个meethod来返回该属性
export default {
props: {
halfWidth: {
type: Boolean,
default: false
},
slice: {
type: Object,
default: () => {}
}
},
methods {
getData() {
return this.slice?.data;
},
getShopifyProduct() {
return this.getData()?.shopifyproduct;
},
},
computed: {
title() {
return this.getShopifyProduct()?.title
},
price() {
return this.getShopifyProduct()?.variants[0]?.price
},
image() {
return this.getShopifyProduct()?.image?.src
},
alt() {
return this.getShopifyProduct()?.image?.alt
},
desc() {
return this.getData()?.short_description[0]?.text
},
handle() {
return this.getShopifyProduct()?.handle
}
}
}
</script>
尝试使用lodash/get
或
函数调用
getShopifyproduct('variants.0.price')
为什么这里需要计算属性?你不能循环数据并显示各个字段吗?
methods: {
getShopifyproduct(key) {
return _get(this.slice.shopifyproduct, key)
}
}
getShopifyproduct('variants.0.price')