javascript - NUXT - 如何更好地重构计算属性
问题描述
我有一个 NUXT 项目,我拥有的一些数据有时会不存在。
但是,计算的属性变得很长,我觉得这不是最佳实践。有没有办法缩短这个时间,或者以某种方式通过传入参数使计算属性动态化而不破坏站点(如果它不存在)?
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,因此您可以创建一个方法来返回它
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>
推荐阅读
- flutter - 带有firebaseauthentification的空指针期望
- node.js - 当从节点发送响应到角度时,返回意味着什么
- python - 使用多处理和 exe (pyinstaller) 时,argparse 抛出错误
- hibernate - 具有额外多对多关系的 JPA 多对多
- c++ - 如何使 rand() 更随机?
- angular - Angular 开发和 TFS
- python - 使用 RS485 和 Modbus(Python 或 LabView)从温度控制器读取和写入数据
- tinkerpop - 哪些 tinkerpop 后端支持 upsert
- python - SQLAlchemy - 值和默认值之间的最小值/最大值
- node.js - node js获取对象数组对象