首页 > 解决方案 > 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>

标签: javascriptobjectnuxt.js

解决方案


由于您的大多数计算属性都依赖于 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>

推荐阅读