微信小程式商城開發之實現商品加入購物車的功能(程式碼)

不言
發布: 2018-08-16 17:01:56
原創
54389 人瀏覽過

這篇文章帶給大家的內容是關於微信小程式商城開發之實現商品加入購物車的功能(代碼) ,有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。

看效果

購物車.gif

#開發計畫

1、商品詳情頁將商品資訊放進入快取
2、購物車頁面讀取快取獲取商品資訊
3、購物車商品計算與刪除快取商品

一、商品詳情頁將商品資訊放入快取

#detail.wxml

登入後複製

綁定bindtap事件將商品加入購物車。

detail.js

/**
   * 加入购物车
   */
  addCar: function (e) {    
    var goods = this.data.goods;
    goods.isSelect=false;    
    var count = this.data.goods.count;    
    var title = this.data.goods.title;    
    if (title.length > 13) {
      goods.title = title.substring(0, 13) + '...';
    }    
    // 获取购物车的缓存数组(没有数据,则赋予一个空数组)  
    var arr = wx.getStorageSync('cart') || [];    
    console.log("arr,{}", arr);    
    if (arr.length > 0) {      
        // 遍历购物车数组  
      for (var j in arr) {        
        // 判断购物车内的item的id,和事件传递过来的id,是否相等  
        if (arr[j].goodsId == goodsId) {          
        // 相等的话,给count+1(即再次添加入购物车,数量+1)  
          arr[j].count = arr[j].count + 1;          
        // 最后,把购物车数据,存放入缓存(此处不用再给购物车数组push元素进去,因为这个是购物车有的,直接更新当前数组即可)  
          try {
            wx.setStorageSync('cart', arr)
          } catch (e) {            
            console.log(e)
          }          
        //关闭窗口
          wx.showToast({            
            title: '加入购物车成功!',            
            icon: 'success',            
            duration: 2000
          });          
        this.closeDialog();          
            // 返回(在if内使用return,跳出循环节约运算,节约性能) 
          return;
        }
      }      
        // 遍历完购物车后,没有对应的item项,把goodslist的当前项放入购物车数组  
      arr.push(goods);
    } else {
      arr.push(goods);
    }    
    // 最后,把购物车数据,存放入缓存  
    try {
      wx.setStorageSync('cart', arr)      
        // 返回(在if内使用return,跳出循环节约运算,节约性能) 
      //关闭窗口
      wx.showToast({        
         title: '加入购物车成功!',        
         icon: 'success',        
         duration: 2000
      });      
        this.closeDialog(); 
      return;
    } catch (e) {      
        console.log(e)
    }
  }
登入後複製

二、購物車頁面讀取快取以取得商品資訊

cart.wxml