简体   繁体   中英

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>

Since most of your computed propeerties depend on shopifyProduct, you ccan create a meethod to return that

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>

try to use lodash/get https://lodash.com/docs/4.17.15#get

import _get from 'lodash/get'

computed: {
  title() {
    return _get(this.slice, 'data.shopifyproduct.title')
  },
  title() {
    return _get(this.slice, 'data.shopifyproduct.variants.0.price')
  },
}

OR

methods: {
  getShopifyproduct(key) {
    return _get(this.slice.shopifyproduct, key)
  }
}

function call

getShopifyproduct('variants.0.price')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM