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

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

不言
不言原創
2018-08-16 17:01:5654612瀏覽

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

看效果

購物車.gif

#開發計畫

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

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

#detail.wxml

<button data-goodid="{{goods.goodsId}}" class="button-addCar" bindtap="addCar" formType="submit">确定</button>

綁定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) + &#39;...&#39;;
    }    
    // 获取购物车的缓存数组(没有数据,则赋予一个空数组)  
    var arr = wx.getStorageSync(&#39;cart&#39;) || [];    
    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(&#39;cart&#39;, arr)
          } catch (e) {            
            console.log(e)
          }          
        //关闭窗口
          wx.showToast({            
            title: &#39;加入购物车成功!&#39;,            
            icon: &#39;success&#39;,            
            duration: 2000
          });          
        this.closeDialog();          
            // 返回(在if内使用return,跳出循环节约运算,节约性能) 
          return;
        }
      }      
        // 遍历完购物车后,没有对应的item项,把goodslist的当前项放入购物车数组  
      arr.push(goods);
    } else {
      arr.push(goods);
    }    
    // 最后,把购物车数据,存放入缓存  
    try {
      wx.setStorageSync(&#39;cart&#39;, arr)      
        // 返回(在if内使用return,跳出循环节约运算,节约性能) 
      //关闭窗口
      wx.showToast({        
         title: &#39;加入购物车成功!&#39;,        
         icon: &#39;success&#39;,        
         duration: 2000
      });      
        this.closeDialog(); 
      return;
    } catch (e) {      
        console.log(e)
    }
  }

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

cart.wxml

<view class="J-shopping-cart-empty" hidden="{{iscart}}"><view class="shopping-cart-empty">
        <view class="bg"></view> 
        <view class="cart"></view>
        <text class=&#39;empty-text&#39;>购物车空空如也</text>  
        <p></p>
        <navigator url="/pages/goods/goods">
         <a href="//m.vip.com" class="button button-primary" >
            去抢购        </a>
        </navigator>
    </view></view> <view class="scroll" hidden="{{hidden}}"><scroll-view class="scroll" scroll-y="true">
  <view class="separate"></view>
  <view wx:for="{{carts}}">
    <view class="cart_container">  
      <view  wx:if="{{!item.isSelect}}">
            <icon class="item-select" bindtap="switchSelect" data-index="{{index}}" data-id="{{index}}"  type="circle" size="20"></icon>
      </view>
      <view wx:elif="{{item.isSelect}}">
            <icon class="item-select" bindtap="switchSelect" data-index="{{index}}" data-id="{{index}}"  type="success" color="#f0145a" size="20"></icon>
      </view>

      <image class="item-image" src="{{item.imgUrl}}"></image>
      <import src="../template/template.wxml" />
      <view class="column">
        <text class="title">{{item.title}}</text>
         <image bindtap="delGoods" id="img{{index}}" data-index="{{index}}" src="../../images/del.png"></image> 
        <view class="row">
          <text class="sku-price">¥{{item.price * item.count}}</text>
          <view class="sku">
              <template is="quantity"  data="{{ ...item,index:index}}" /> 
          </view>
        </view>

      </view>
    </view>
    <view class="separate"></view>
  </view></scroll-view></view>
 <view class="bottom_total" hidden="{{hidden}}">
  <view class="bottom_line"></view>

  <view class="row">

    <view  wx:if="{{!isAllSelect}}">
            <icon class="item-allselect" bindtap="allSelect" type="circle" size="20"></icon>
      </view>
      <view wx:elif="{{isAllSelect}}">
            <icon class="item-allselect" bindtap="allSelect" type="success" color="#f0145a" size="20"></icon>
      </view>
    <text class="small_text">全选</text>
    <text>合计:¥ </text>
    <text class="price">{{totalMoney}}</text>
    <button class="button-red" bindtap="toBuy" formType="submit">去结算      </button>
  </view></view>

cart.wxss

#
 @import "../template/template.wxss"; 
page{  
  background: #f3f4f5;  
  /* font-size: 37.5px;  */
}  
 .column image {  
     width:33rpx;  
     height:35rpx;  
     display:inline-block;  
     overflow:hidden;  
     float:right;  
     margin-top: -40rpx;  
     margin-left:400rpx;
} 
 .J-shopping-cart-empty{    
     margin: 0;    
     padding: 0;    
     border: 0;    
     font: inherit;    
     font-size: 100%;    
     vertical-align: baseline;
}
.shopping-cart-empty {   
    height: 250px;    
    padding-top: 3.2rem;    
    padding-bottom: 1.6rem;    
    background-color: #fff;    
    text-align: center;    
    position: relative;
} 
.shopping-cart-empty .bg{    
    position: absolute;    
    width: 16.29333rem;    
    height: 6.73333rem;    
    
    background: transparent url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAm0AAAEXAQMAAADFlOHHAAAABlBMVEUAAAAAAAClZ7nPAAAAAnRSTlMAFRtOKdMAAArmSURBVHja5ZxNiBzHFcf/b2pcvUSt6UkOoYWG7RUE5+LgXtvIIzTsrGXIIST3HAxuWSbxYSEjCI4CiqY2MrIPSywiQhRyiHwLIQdBgiNwcMpswDYoiQkEBDa4iME5ug0JjM1oKofdmf6q7Z7proAgfezp+fXrV69evffqA/jfX5es0tjEKs57xSrusmv1W5VVXIDLNnET9rFFmiMDbhG3hUnLIi52JLP4rWILFnHrFNvEXXJuw7Fnw3Lgo2Ovv1LsomevvzrCRWiLRmoLHJE9M5miBWmtS7C7YGQNF6+7IBK2VCcvuaCr1hr2LeUC16zh3hZt4K49s0Mb+KY13Ajc5jAb2cWF4MDIIq6F2l12VrjTBauN83Thlp/BUXHQBJyjuuD4X4XeFMwI2Fg4hNzr3zvA0dToPTQTRYE/FQmuk//D/XcA/qE2RljjmBn6+o9E4u76ud+O6U+0nunPzcLhogHnyUS6osV8ov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baL+7Jd3Lpd3Ar52X8BXSURa9qZGGgAAAAASUVORK5CYII=);    
    left: 50%;    
    -webkit-transform: translateX(-50%);    
    transform: translateX(-50%);      
    background-size: 100%;    
    top: 0;
} 
.shopping-cart-empty .cart{        
    width: 5.83333rem;    
    height: 7.46rem;    
    background: transparent url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAANwAAAEaCAMAAABNQsmuAAAAY1BMVEUAAAD6AIr32prUAHU4ByEmCxhWIjd0AEHpAIG6NXLwAIXsAIPjAnvjAH1oNk/4AIqvAGHEAGyonp2npKbpAYKLhon73Kz+66X5357/odv74577pM/yVq7kAH/6AIvzAIf/m9Nba+mLAAAAHXRSTlMA6f7rJRcKgeEdlnA+ukLCnlxgwvOWapTY37Kw+AL3QMkAAAdeSURBVHja7V3bcqM6EARHKEiAMBc7tyX2/3/l2iAwztlUIZCQ1EfzsE9bLnc0PT3TujiKvAjKItRgn4fDOyY8ej7cAxKdxHY41IDY3g5Q4BhP2yL/iQ0jLfO0u0WbPWPDWLik6PpIxRzbG0Y5EfEA7nJ81JJPlEopvidwZzBoD3Ddny80aFFEygFb++d6BYN2r5btsHDXW3zhtZK3ehn32K4feG2JuE7xhQwObuno+QHuesJi3Nv7YQauQVq0z17cAMHdF22YAL7A0nJctHtTQvMPpIJCz++HB7YoqiU6iGJ5nqAd3obJ53yD93GGGOKmlHwf14pSxiiFAgfpccmR+40CYhuW7tf5JhGel8v6zH5dNtKcItwgTUNw0dG6SYDRMRaF8Hj5gMElJ+SqmTQNBUZXN8i0q6GrJo3AAxkgQSberWhCCx40uhpazkMfHcLRZgW7jca2VpDRsUYA0y44KyFC7F9UsNWuBkaH7RlhS/kJ2VNJ4B2xECGCkO8p5NDgWAAXwDnXgdXIMh5alBAh9gwB3KBQYKOBIvsMDHrhkN2vYDKEviuM4PupN26hpCdgEUDeNKYU8yIFFbBrxk4NrGcimlMNmJBMDP8meDQ74Vb+pKlrgZeNlN0xUYLYRt5qI2pppHWDeweENMBOe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591dJZ0UuXSLZ/h7MAqVY5v+hBXXSKZldu+mKPWrKyV6bZPcdSaZZ2GrHSUdHLhNmalo2/NypucxdbPcdElku9jpJtfpTm6d2qWlFoY5yTpEt5pWjhJum/h3LqlOuqAY6QbsbVaRminBtakijtdhOtl3B3SUcLHN0IKPZnEXCEdJVncaV23yBGXKCE5n6C12rCNpBPEXuQZnz39lOrDJknXxdbix3NKhc5ToMyp97JSzZ5H4RC0QncLf3QEWasf2jiwWgZ2Q5aZGLwk6VJ7URyPlalXN6XSMUthtq09XvDfmsX8fdfctZnOBOmQf8oAOi/9enVJNS9jzKWTTQoo6yz/+p7hpZNDnUBeOsyKSeTIyglwYoKu3fiwegnJu9ERbREVgU5mSkko7tp1F57jweMPO6XIE0qxEGYzE7MtsypnyY5h+m+Z/3QxLzuGeacjs+hAH42nJuPW4KU7MO8Gr4UFd4NX3fDtDrDdzwvIM14ULztGAepzhAgRIkSIECH0Gg+U5czYxHr78JxZG4dZP5i33IjJnvSjVVtYcvBHJ9NIP8tK/afY1mAzsXNHytlhLws5Wc5/mlCzUUv5fNDZ/z3D16dpTnPukO/9R9R5PBtFmncQsuf5e++iQsvnn8wUxrLSQl4yk+ASy+B+pqXelcssgxsOhE0FRe+9g/yZc7v/TrZ4Mi81Cx0p97Vi/xPc3MKN9/dtLdx8u87AVvKMdamd7nLc0DJx0YeOWxK2OueIZUVh5uhxD48XhcrE8ReAb/tmFJQfqgAAAABJRU5ErkJggg==) no-repeat;  
    background-size: 100%;    
    margin: 0 auto;
}  
.shopping-cart-empty .button {   
    width: 8.46667rem;    
    height: 1.5rem;    
    display: block;    
    margin: 20rpx auto;
}
.empty-text {    
    font-size: .64667rem;    
    color: #222;    
    margin-top: .53333rem;    
    line-height: .74667rem;    
    font-weight: 400;
}
.button-primary {    
    border: 1px solid #de3c96;    
    color: #de3c96;    
    text-decoration: none;    
    text-align: center;    
    display: block;    
    border-radius: .21267rem;    
    line-height: 1.5rem;    
    -webkit-appearance: none;    
    background: none;    
    padding: 0 .26667rem;    
    margin: 0;    
    white-space: nowrap;    
    position: relative;    
    text-overflow: ellipsis;    
    font-size: .74333rem;    
    font-family: inherit;    
    cursor: pointer;    
    user-select: none;
} 


.cart_container {  
    display: flex;  
    flex-direction: row;  
    background-color: #FFFFFF;  
    margin-bottom: 10rpx;
}
.scroll {   
    margin-bottom: 120rpx; 
}
.column {  
    display: flex;  
    flex-direction: column;
}
.row { 
    display: flex;  
    flex-direction: row;   
    align-items: center;
}
.sku {  
    margin-left: 100rpx;  
    position: absolute;  
    right: 30rpx;  
    margin-top: 30rpx; 
}
.sku-price {  
    color: red;  
    position: relative;   
    margin-top: 30rpx; 
}
.price {  
    color: red;  
    position: relative;
}
.title {  
    font-size: 32rpx;  
    margin-top: 40rpx;
}
.small_text {  
    font-size: 28rpx;  
    margin-right: 40rpx;  
    margin-left: 25rpx;
}
.item-select {  
    width: 40rpx;  
    height: 40rpx;  
    margin-top: 90rpx;  
    margin-left: 20rpx;
}
.item-allselect {  
    width: 40rpx;  
    height: 40rpx; 
    margin-left: 20rpx;   
    margin-top:25rpx;   
}
.item-image {  
    width: 180rpx;  
    height: 180rpx;  
    margin: 20rpx;
} 
.bottom_line {  
    width: 100%;  
    height: 2rpx;  
    background: lightgray;
} 
.bottom_total {  
    position: fixed;  
    display: flex;  
    flex-direction: column;  
    bottom: 0;  
    width: 100%;  
    height: 120rpx;  
    line-height: 120rpx;  
    background: white;  /* margin-top: 300rpx; */
    border-top: 1rpx solid #ccc;  z-index: 99;
}
.button-red {  
    background-color: #f0145a; 
    position: fixed;  
    right: 0;  
    color: white;  
    text-align: center;  
    display: inline-block;  
    font-size: 30rpx;  
    border-radius: 0rpx;  
    width: 30%;  
    height: 120rpx;  
    line-height: 120rpx;  /* border: 1rpx solid #ccc; */
}

cart.js

/**
   * 页面的初始数据
   */
  data: {    
    carts: [], //数据 
    iscart: false,    
    hidden: null,    
    isAllSelect: false,    
    totalMoney: 0,
  },
onShow: function () {    
    // 获取产品展示页保存的缓存数据(购物车的缓存数组,没有数据,则赋予一个空数组)  
    var arr = wx.getStorageSync(&#39;cart&#39;) || [];    
    console.info("缓存数据:"+arr);    // 有数据的话,就遍历数据,计算总金额 和 总数量  
    if (arr.length > 0) {      
        // 更新数据  
      this.setData({        
        carts: arr,        
        iscart: true,        
        hidden: false
      });      
        console.info("缓存数据:" + this.data.carts);
    }else{      
        this.setData({        
            iscart: false,        
            hidden: true,
      });
    }
  },

三、購物車商品計算與刪除快取商品

cart.js

//勾选事件处理函数  
  switchSelect: function (e) {    
    // 获取item项的id,和数组的下标值  
    var Allprice = 0, i = 0;    
    let id = e.target.dataset.id,

      index = parseInt(e.target.dataset.index);    
    this.data.carts[index].isSelect = !this.data.carts[index].isSelect;    //价钱统计
    if (this.data.carts[index].isSelect) {      
        this.data.totalMoney = this.data.totalMoney + (this.data.carts[index].price * this.data.carts[index].count);
    }    else {      
        this.data.totalMoney = this.data.totalMoney - (this.data.carts[index].price * this.data.carts[index].count);
    }    
    //是否全选判断
    for (i = 0; i < this.data.carts.length; i++) {
      Allprice = Allprice + (this.data.carts[index].price * this.data.carts[index].count);
    }    
    if (Allprice == this.data.totalMoney) {      
        this.data.isAllSelect = true;
    }    else {      
        this.data.isAllSelect = false;
    }    
    this.setData({      
        carts: this.data.carts,      
        totalMoney: this.data.totalMoney,      
        isAllSelect: this.data.isAllSelect,
    })
  },  
    //全选
  allSelect: function (e) {   
     //处理全选逻辑
    let i = 0;    
     if (!this.data.isAllSelect) {      
         this.data.totalMoney = 0;      
         for (i = 0; i < this.data.carts.length; i++) {        
             this.data.carts[i].isSelect = true;        
             this.data.totalMoney = this.data.totalMoney + (this.data.carts[i].price * this.data.carts[i].count);

      }
    }    else {      
        for (i = 0; i < this.data.carts.length; i++) {        
            this.data.carts[i].isSelect = false;
      }      
            this.data.totalMoney = 0;
    }    
            this.setData({      
                carts: this.data.carts,      
                isAllSelect: !this.data.isAllSelect,      
                totalMoney: this.data.totalMoney,
    })
  },  // 去结算
  toBuy() {
    wx.showToast({      
       title: &#39;去结算&#39;,      
       icon: &#39;success&#39;,      
       duration: 3000
    });    
    this.setData({      
       showDialog: !this.data.showDialog
    });
  },  //数量变化处理
  handleQuantityChange(e) {    
      var componentId = e.componentId;    
      var quantity = e.quantity;    
      this.data.carts[componentId].count.quantity = quantity;    
      this.setData({      
         carts: this.data.carts,
    });
  },  
   /* 减数 */
  delCount: function (e) {    
   var index = e.target.dataset.index;    
   console.log("刚刚您点击了加一");    
   var count = this.data.carts[index].count;    // 商品总数量-1
    if (count > 1) {      
       this.data.carts[index].count--;
    }    
       // 将数值与状态写回  
    this.setData({      
       carts: this.data.carts
    });    
       console.log("carts:" + this.data.carts);    
       this.priceCount();
  },  
       /* 加数 */
  addCount: function (e) {    
       var index = e.target.dataset.index;    
       console.log("刚刚您点击了加+");    
       var count = this.data.carts[index].count;    // 商品总数量+1  
    if (count < 10) {      
       this.data.carts[index].count++;
    }    
       // 将数值与状态写回  
    this.setData({      
       carts: this.data.carts
    });    
       console.log("carts:" + this.data.carts);    
       this.priceCount();
  }, 
  priceCount: function (e) {    
      this.data.totalMoney = 0;    
      for (var i = 0; i < this.data.carts.length; i++) {      
      if (this.data.carts[i].isSelect == true) {        
          this.data.totalMoney = this.data.totalMoney + (this.data.carts[i].price * this.data.carts[i].count);
      }

    }    
          this.setData({      
              totalMoney: this.data.totalMoney,
        })
  },  
  /* 删除item */
  delGoods: function (e) {    
      this.data.carts.splice(e.target.id.substring(3),1);    // 更新data数据对象  
    if (this.data.carts.length > 0) {      
          this.setData({        
              carts: this.data.carts
      })
      wx.setStorageSync(&#39;cart&#39;, this.data.carts);      
              this.priceCount();
    } else {      
              this.setData({            
                  cart: this.data.carts,        
                  iscart: false,        
                  hidden: true,
      })
      wx.setStorageSync(&#39;cart&#39;, []);
    }
  }

相關推薦:

微信小程式商城開發之動態API把商品分類(程式碼)

#微信小程式商城開發之動態API實作特賣商品的串流佈局程式碼


以上是微信小程式商城開發之實現商品加入購物車的功能(程式碼)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn