Kaynağa Gözat

✨ feat(goods-detail): 添加规格选项支持并优化按钮禁用逻辑

- 新增子商品列表查询,用于判断商品是否包含规格选项
- 根据是否有规格选项动态调整加入购物车和立即购买按钮的禁用条件
- 当存在规格选项时,按钮禁用取决于所选规格的库存;否则取决于主商品库存
yourname 1 ay önce
ebeveyn
işleme
9c66087fe0
1 değiştirilmiş dosya ile 38 ekleme ve 2 silme
  1. 38 2
      mini/src/pages/goods-detail/index.tsx

+ 38 - 2
mini/src/pages/goods-detail/index.tsx

@@ -103,6 +103,30 @@ export default function GoodsDetailPage() {
     staleTime: 5 * 60 * 1000,
   })
 
+  // 获取子商品列表,用于判断是否有规格选项
+  const { data: childGoodsData } = useQuery({
+    queryKey: ['goods', goodsId, 'children'],
+    queryFn: async () => {
+      const response = await goodsClient[':id'].children.$get({
+        param: { id: goodsId },
+        query: {
+          page: 1,
+          pageSize: 100, // 获取所有子商品,假设不会超过100个
+          sortBy: 'createdAt',
+          sortOrder: 'ASC'
+        }
+      })
+      if (response.status !== 200) {
+        throw new Error('获取子商品列表失败')
+      }
+      return response.json()
+    },
+    enabled: goodsId > 0,
+    staleTime: 5 * 60 * 1000,
+  })
+
+  const hasSpecOptions = childGoodsData && childGoodsData.data && childGoodsData.data.length > 0
+
   // 商品轮播图
   const carouselItems = goods?.slideImages?.map((file: any) => ({
     src: file.fullUrl || '',
@@ -478,14 +502,26 @@ export default function GoodsDetailPage() {
           <Button
             className="add-cart-btn"
             onClick={handleAddToCart}
-            disabled={goods.stock <= 0}
+            disabled={
+              !goods
+                ? true
+                : hasSpecOptions
+                  ? !selectedSpec || selectedSpec.stock <= 0
+                  : goods.stock <= 0
+            }
           >
             加入购物车
           </Button>
           <Button
             className="buy-now-btn"
             onClick={handleBuyNow}
-            disabled={goods.stock <= 0}
+            disabled={
+              !goods
+                ? true
+                : hasSpecOptions
+                  ? !selectedSpec || selectedSpec.stock <= 0
+                  : goods.stock <= 0
+            }
           >
             立即购买
           </Button>