tapAddCart: function (e) {
this.addCart(e.target.dataset.id);//传入商品id值到addCart函数中
},
tapReduceCart: function (e) {
this.reduceCart(e.target.dataset.id);//传入商品id值到reduceCart函数中
},
addCart: function (id) {
// console.log("id" + id);//获取id值,用来区分菜品
var num = this.data.cart.list[id] || 0;//添加菜品看是否此菜品已经添加,未有添加就赋值0给num
this.data.cart.list[id] = num + 1;//此菜品数+1
this.countCart();//调用countCart函数,计算商品的价格,数量。
},
reduceCart: function (id) {
var num = this.data.cart.list[id] || 0;//看此id菜品数量是否存在,不存在赋值0,
if (num <= 1) {
delete this.data.cart.list[id];//当菜品数量少于等于1的时候删除菜品
} else {
this.data.cart.list[id] = num - 1;//大于1的时候,数量减少1
}
this.countCart();//执行countCart函数,计算商品的价格,数量。
},
countCart: function () {
var count = 0,
total = 0;//初始化count total 此count和total与data.cart里的total,count不同。
for (var id in this.data.cart.list) {
var goods = this.data.goods[id];//将选择的商品信息赋值给goods
count += this.data.cart.list[id];//此商品数量+1
total += goods.price * this.data.cart.list[id];//此商品的总价格
}
this.data.cart.count = count;//将商品总数量赋值
this.data.cart.total = total;//将商品总价格赋值
this.setData({
cart: this.data.cart//设置data的cart数据
});
console.log(this.data.cart);
},