- Published on
小程序-建立购物车表
- Authors
- Name
- zoe
这是我看别人代码总结出来的方法:思路是 一,当用户在商品详情页点击加入购物车时,建立一张表,存放在 storage 空间中。 二,每次进入商品详情页时,也就是在 onload 里面,再次读取这个数组,用 getStorage 把这个数组赋值给 data 中我们定义好的 shopCatInfo. 这是在商品详情页的逻辑。购物车页面的逻辑等下再讲。 以下是具体代码 一: 先定义 data
data:{
shopCarInfo: {},
shopNum:0,
buyNumber:0,
buyNumMin:0,
buyNumMax:50,
}
建立一张表 produce 是我请求到的后台商品详情数据。
var shopCarMap={};
shopCarMap.goods_name=this.data.product.productName;
shopCarMap.goods_id=this.data.product.productId;
shopCarMap.pic= this.data.product.productIcon;
shopCarMap.price= this.data.product.salePrice;
shopCarMap.number=this.data.buyNumber;
shopCarMap.active = true;//购物车页面要用到的
shopCarMap.left="";、、购物车页面要用到的
将当前 data 中的 shopCarInfo 存入
var shopCarInfo=this.data.shopCarInfo;
//判断一下这个data.shopCarInfo
if(!shopCarInfo.shopNum){
shopCarInfo.shopNum=0;
}
if(!shopCarInfo.shopList){
shopCarInfo.shopList=[];
}
如果加入相同商品
var hasSameGoodsIndex=-1;//如果又加入相同的商品
for(let i=0;i<shopCarInfo.shopList.length;i++){
var tmpShopCarMap=shopCarInfo.shopList[i];
console.log('上一次留下的购物车'+shopCarInfo.shopList[i].goods_name);
if(tmpShopCarMap.goods_id==shopCarMap.goods_id)
{//通过id判断购物车里是否已经有和当前加入商品相同的商品
hasSameGoodsIndex=i;
shopCarMap.number=shopCarMap.number+tmpShopCarMap.number;
break;
}
}
算一共有多少商品
//算总的多少件商品 以前的购物车商品数加现在新增加的
shopCarInfo.shopNum=shopCarInfo.shopNum+this.data.buyNumber;
console.log(hasSameGoodsIndex);
if(hasSameGoodsIndex>-1){
shopCarInfo.shopList.splice(hasSameGoodsIndex,1,shopCarMap);
}else{
shopCarInfo.shopList.push(shopCarMap);
}
return shopCarInfo;//返回我们建立好的表
}
二:
addShopCar:function(){
if(this.data.buyNumber<1){
wx.showModal({
title:'提示',
content:'购买数量不能为0!',
showCancel:false
})
return
}
var shopCarInfo=this.buildShopCarInfo();
this.setData({
shopCarInfo:shopCarInfo,
shopNum:shopCarInfo.shopNum
})
//写入本地存储
wx.setStorage({
key:'shopCarInfo',
data:shopCarInfo
})
this.close_popup_tap();
wx.showToast({
title:'加入购物车',
icon:'sucess',
duration:2000
})
},