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); },
