Administrator
发布于 2025-09-11 / 16 阅读
0
0

微信小程序立即购买和添加到购物车j s

Page({

data: {

ProductProperty: { // 商品属性数据结构

properties: [

{

name: "颜色",

items: [

{ id: "1", name: "红色", active: false }, // 初始未选中

{ id: "2", name: "蓝色", active: false }

]

},

// 其他属性...

]

},

cartItems: [] // 购物车数据

},

// 属性选择事件处理

labelItemTap(e) {

// 从事件对象中获取属性索引和选项索引

const { propertyindex, propertychildindex } = e.currentTarget.dataset;

const properties = this.data.ProductProperty.properties;

// 切换选中状态:同属性下其他选项取消选中

properties[propertyindex].items.forEach((item, idx) => {

item.active = (idx === propertychildindex);

});

// 更新视图层数据

this.setData({

'ProductProperty.properties': properties

});

},

// 立即购买处理

buyNow() {

// 验证是否完成所有属性选择

const selectedProps = this.getSelectedProperties();

if (!selectedProps) {

this.showToast('请选择所有商品属性');

return;

}

// 构建订单信息对象

const orderInfo = {

productId: '12345',

selectedProps: selectedProps,

quantity: 1,

price: 199.00,

timestamp: Date.now()

};

// 页面跳转(携带订单信息)

wx.navigateTo({

url: /pages/orderConfirm/orderConfirm?orderInfo=${JSON.stringify(orderInfo)}

});

},

// 加入购物车处理

addToCart() {

// 验证属性选择

const selectedProps = this.getSelectedProperties();

if (!selectedProps) {

this.showToast('请选择所有商品属性');

return;

}

// 构建购物车项

const cartItem = {

id: cart_${Date.now()}, // 生成唯一ID

productId: '12345',

selectedProps: selectedProps,

quantity: 1,

price: 199.00,

timestamp: Date.now()

};

// 更新购物车数据

const newCart = [...this.data.cartItems, cartItem];

this.setData({ cartItems: newCart }, () => {

this.showToast('已添加到购物车');

// 持久化存储

wx.setStorageSync('cartItems', newCart);

});

},

// 获取选中属性集合

getSelectedProperties() {

const properties = this.data.ProductProperty.properties;

const selected = [];

// 遍历验证每个属性是否已选择

let allSelected = true;

properties.forEach(prop => {

const activeItem = prop.items.find(item => item.active);

if (activeItem) {

selected.push({

name: prop.name,

value: activeItem.name

});

} else {

allSelected = false;

}

});

// 返回选择结果或null

return allSelected ? selected : null;

},

// 统一提示工具方法

showToast(title) {

wx.showToast({

title: title,

icon: 'none',

duration: 2000

});

}

})


评论