微信小程序,購物車模塊代碼解讀


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM