diff --git a/packages/shop/search/index.vue b/packages/shop/search/index.vue index c06be7eb..68840013 100644 --- a/packages/shop/search/index.vue +++ b/packages/shop/search/index.vue @@ -78,7 +78,7 @@ {{ getPriceRange(item.commodity_goods_info_list) }} - @@ -128,7 +128,7 @@ {{ ite.sales_price }} - @@ -293,25 +293,49 @@ export default { }, // 处理商品数量变化 handleQuantityChange(val, item) { - // 先在前端直接更新数量,确保页面显示及时变化 - // 注意:这里的val可能是直接的数值,也可能是包含value属性的对象 const quantity = typeof val === 'object' && val !== null && 'value' in val ? val.value : val; - + + // 检查库存数量 + let currentQuantity = 0; + let stockQuantity = 0; + let goodsToUpdate = null; + // 对于有规格的主商品(绑定到items.commodity_goods_info_list[0].quantity) - if (item.commodity_goods_info_list && item.commodity_goods_info_list.length) { + if ( + item.commodity_goods_info_list && + item.commodity_goods_info_list.length + ) { this.goodsId = item.commodity_goods_info_list[0].id; - // 使用$set确保响应式更新 - this.$set(item.commodity_goods_info_list[0], 'quantity', quantity); + currentQuantity = item.commodity_goods_info_list[0].quantity || 0; + stockQuantity = item.commodity_goods_info_list[0].stock_quantity || 0; + goodsToUpdate = item.commodity_goods_info_list[0]; } // 对于规格列表中的商品(绑定到ite.quantity) else { this.goodsId = item.id; - // 使用$set确保响应式更新 - this.$set(item, 'quantity', quantity); + currentQuantity = item.quantity || 0; + stockQuantity = item.stock_quantity || 0; + goodsToUpdate = item; } - + + // 直接检查新数量是否超过库存,如果超过则不允许修改 + if (quantity > stockQuantity) { + uni.showToast({ + title: "库存不足", + icon: 'none' + }); + // 强制重置数量为当前值或库存值,确保UI上显示的数量不会超过库存 + this.$nextTick(() => { + this.$set(goodsToUpdate, 'quantity', Math.min(currentQuantity, stockQuantity)); + }); + return; + } + + // 使用$set确保响应式更新 + this.$set(goodsToUpdate, 'quantity', quantity); + const params = { - user_id: uni.getStorageSync('userId'), + user_id: uni.getStorageSync("userId"), goods_id_and_count: [ { goods_id: this.goodsId, @@ -319,24 +343,26 @@ export default { }, ], }; - - request(apiArr.updateCar, 'POST', params).then((res) => { + + // 发送请求更新后端数据 + request(apiArr.updateCar, "POST", params).then((res) => { console.log(res); - // 更新购物车数据 + // 先更新购物车数据 this.getShopCarList(); - - // 延迟时间,确保goodsDetail已经更新 + + // 延迟一小段时间,确保goodsDetail已经更新 setTimeout(() => { // 重新同步商品列表中的数量 this.syncGoodsQuantities(); }, 100); - + uni.showToast({ - title: '操作成功!', + title: "操作成功!", success() { }, }); }); }, + // 同步商品列表中的数量与购物车数据 syncGoodsQuantities() { // 遍历所有商品,同步数量