一般都会把商品信息存储于缓存之中,web端cookie可存的容量较小,sessionStorage关闭当前页面便会销毁数据,所以一般选择localStorage存储购物车的数据,小程序直接使用get/setStorageSync,本例使用uni-App框架。
addToCart() {
// 1 获取缓存中的购物车数组,初始为不存在,所以会得到一个空数组
let cart = uni.getStorageSync('cart') || [];
// 2 判断 商品对象是否存在于购物车数组中
let index = cart.findIndex(v => v.id === this.product.id);
if (index === -1) {
//3 不存在 第一次添加
this.product.num = 1;
this.product.checked = true;
cart.push(this.product);
} else {
// 4 已经存在购物车数据 执行 num++
cart[index].num++;
}
// 5 把购物车重新添加回缓存中
uni.setStorageSync('cart', cart);
},
product为商品对象,格式大体如下
product: {
name: '春季长袖白色t恤 ',
price: 1,
imgUrl: 'url',
id: Math.random(),
},