Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript NUXT-如何更好地重构计算属性_Javascript_Object_Nuxt.js - Fatal编程技术网

Javascript NUXT-如何更好地重构计算属性

Javascript NUXT-如何更好地重构计算属性,javascript,object,nuxt.js,Javascript,Object,Nuxt.js,我有一个NUXT项目,我有的数据有时不存在。 然而,计算的属性越来越长,我觉得出于某种原因,这不是最佳实践。有没有一种方法可以缩短这个时间,或者在不破坏站点(如果站点不存在)的情况下,通过传入参数使计算属性动态化 export default { props: { halfWidth: { type: Boolean, default: false }, slice: { type: Object, default: (

我有一个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,因此您可以创建一个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')