index.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import SkuList from './SkuList.vue'
  2. import { Spu } from '@/api/mall/product/spu'
  3. interface PropertyAndValues {
  4. id: number
  5. name: string
  6. values?: PropertyAndValues[]
  7. }
  8. interface RuleConfig {
  9. // 需要校验的字段
  10. // 例:name: 'name' 则表示校验 sku.name 的值
  11. // 例:name: 'productConfig.stock' 则表示校验 sku.productConfig.name 的值,此处 productConfig 表示我在 Sku 上扩展的属性
  12. name: string
  13. // 校验规格为一个毁掉函数,其中 arg 为需要校验的字段的值。
  14. // 例:需要校验价格必须大于0.01
  15. // {
  16. // name:'price',
  17. // rule:(arg: number) => arg > 0.01
  18. // }
  19. rule: (arg: any) => boolean
  20. // 校验不通过时的消息提示
  21. message: string
  22. }
  23. /**
  24. * 获得商品的规格列表 - 商品相关的公共函数
  25. *
  26. * @param spu
  27. * @return PropertyAndValues 规格列表
  28. */
  29. const getPropertyList = (spu: Spu): PropertyAndValues[] => {
  30. // 直接拿返回的 skus 属性逆向生成出 propertyList
  31. const properties: PropertyAndValues[] = []
  32. // 只有是多规格才处理
  33. if (spu.specType) {
  34. spu.skus?.forEach((sku) => {
  35. sku.properties?.forEach(({ propertyId, propertyName, valueId, valueName }) => {
  36. // 添加属性
  37. if (!properties?.some((item) => item.id === propertyId)) {
  38. properties.push({ id: propertyId!, name: propertyName!, values: [] })
  39. }
  40. // 添加属性值
  41. const index = properties?.findIndex((item) => item.id === propertyId)
  42. if (!properties[index].values?.some((value) => value.id === valueId)) {
  43. properties[index].values?.push({ id: valueId!, name: valueName! })
  44. }
  45. })
  46. })
  47. }
  48. return properties
  49. }
  50. export { SkuList, PropertyAndValues, RuleConfig, getPropertyList }