// ...(原有导入保持不变)
Page({
data: {
// ...(原有data保持不变)
quantity: 1, // 新增商品数量控制
cartCount: 0, // 购物车商品总数(用于tabBar徽标)
},
onLoad(options) {
// ...(原有onLoad逻辑)
this.loadCartData(); // 加载购物车数据
},
// 加载购物车数据
loadCartData() {
const cartData = wx.getStorageSync('cart') || [];
this.setData({
cart: cartData,
cartCount: cartData.reduce((total, item) => total + item.quantity, 0)
});
},
// 数量控制
increaseQuantity() {
this.setData({ quantity: this.data.quantity + 1 });
},
decreaseQuantity() {
if (this.data.quantity > 1) {
this.setData({ quantity: this.data.quantity - 1 });
}
},
// 立即购买
buyNow() {
const selectedProps = this.getSelectedProperties();
if (!selectedProps) {
this.showToast('请选择所有商品属性');
return;
}
// 库存校验
if (this.data.quantity > this.data.goodsDetail.basicInfo.stores) {
this.showToast('库存不足');
return;
}
// 构建订单信息
const orderInfo = {
productId: this.data.goodsDetail.basicInfo.id,
selectedProps: selectedProps,
quantity: this.data.quantity,
price: this.data.goodsDetail.basicInfo.minPrice,
timestamp: Date.now()
};
// 跳转订单页
wx.navigateTo({
url: /pages/orderConfirm/orderConfirm?orderInfo=${JSON.stringify(orderInfo)}
});
},
// 加入购物车
addToCart() {
const selectedProps = this.getSelectedProperties();
if (!selectedProps) {
this.showToast('请选择所有商品属性');
return;
}
// 库存校验
if (this.data.quantity > this.data.goodsDetail.basicInfo.stores) {
this.showToast('库存不足');
return;
}
// 构建购物车商品对象
const cartItem = {
id: this.data.goodsDetail.basicInfo.id,
name: this.data.goodsDetail.basicInfo.name,
price: this.data.goodsDetail.basicInfo.minPrice,
pic: this.data.goodsDetail.basicInfo.pic,
quantity: this.data.quantity,
selectedProps: selectedProps,
timestamp: Date.now()
};
// 更新购物车数据
let cart = this.data.cart;
const index = cart.findIndex(item =>
item.id === cartItem.id &&
this.propsEqual(item.selectedProps, cartItem.selectedProps)
);
if (index > -1) {
// 已存在则增加数量
cart[index].quantity += cartItem.quantity;
} else {
// 新增商品
cart.push(cartItem);
}
// 更新存储和界面
this.setData({
cart: cart,
cartCount: cart.reduce((total, item) => total + item.quantity, 0)
});
wx.setStorageSync('cart', cart);
this.showToast('已加入购物车');
},
// 属性选择处理
labelItemTap(e) {
// ...(原有属性选择逻辑)
// 更新后关闭弹窗(可选)
// this.closePopup();
},
// 属性对比辅助方法
propsEqual(props1, props2) {
if (props1.length !== props2.length) return false;
return props1.every(p =>
props2.some(q =>
p.name === q.name && p.value === q.value
)
);
},
// 统一提示工具
showToast(title) {
wx.showToast({ title, icon: 'none', duration: 2000 });
}
});