diff --git a/src/views/commodity-detail/components/shopping-cart.vue b/src/views/commodity-detail/components/shopping-cart.vue index 5d6f4e1..5f15557 100644 --- a/src/views/commodity-detail/components/shopping-cart.vue +++ b/src/views/commodity-detail/components/shopping-cart.vue @@ -67,6 +67,7 @@ const categoryOrder = ref([]) // 类目 const curSelection = ref>({}) const curPageData = ref({ price: 0, imageUrl: '', num: 0 }) const formData = ref({ skuId: NaN, num: 1 }) +const skuSelectionList = ref; stock: number }>>([]) // 设置pathset const buildSignature = (order: string[], selection: Record) => order.map((name) => `${name}:${selection[name] ?? ''}`).join('|') @@ -89,8 +90,13 @@ const updateOptionDisabled = () => { Object.entries(skuData.value).forEach(([categoryName, options]) => { options.forEach((opt) => { const trialSelection = { ...curSelection.value, [categoryName]: opt.label } - const match = commodityData.value[buildSignature(categoryOrder.value, trialSelection)] - opt.disabled = !match || (match.num ?? 0) <= 0 + const availableStock = skuSelectionList.value + .filter(({ selection }) => + categoryOrder.value.every((name) => !trialSelection[name] || selection[name] === trialSelection[name]), + ) + .reduce((sum, sku) => sum + sku.stock, 0) + opt.num = availableStock + opt.disabled = availableStock <= 0 }) }) } @@ -102,6 +108,7 @@ const handleGetSkuList = (list: SkuType[]) => { const order = list[0]?.vvSkuPropertyValueList?.map((vv) => vv.productPropertyName) || [] categoryOrder.value = order let firstSelection: Record = {} + const selectionList: Array<{ selection: Record; stock: number }> = [] list.forEach((sku, index) => { // 第一次默认选择 @@ -122,28 +129,30 @@ const handleGetSkuList = (list: SkuType[]) => { price: sku.promotionPrice, num: sku.stock, } + selectionList.push({ selection, stock: sku.stock }) // 生成展示的数组 - sku.vvSkuPropertyValueList.forEach((vv, idx) => { + sku.vvSkuPropertyValueList.forEach((vv) => { if (!result[vv.productPropertyName]) result[vv.productPropertyName] = [] const bucket = result[vv.productPropertyName] const sid = buildOptionSid(vv) const existing = bucket.find((item) => item.sid === sid) - const isLeafProperty = idx === order.length - 1 if (existing) { // 非叶子类目需要展示该类目下所有 SKU 的累计库存;叶子类目保持当前 SKU 库存 - existing.num = isLeafProperty ? sku.stock : existing.num + sku.stock + existing.num += sku.stock } else { bucket.push({ sid, label: vv.productPropertyValue, num: sku.stock, - disabled: isLeafProperty ? sku.stock <= 0 : false, + disabled: false, }) } }) }) + skuSelectionList.value = selectionList + return { result, commodityMap, firstSelection } }