Wednesday, 7 April 2021

NUXT - How to better refactor computed properties

I have a NUXT project, and some data I have will sometimes not exists.
However, the computed properties is getting quite long, and I feel it isn't the best practice some reason. Is there a way to shorten this, or somehow make the computed properties dynamic by passing in arguments without breaking the site if it doesn't exists?

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>


from NUXT - How to better refactor computed properties

No comments:

Post a Comment