WeChat Mini Program Mall Development to Implement the Function of Adding Products to the Shopping Cart (Code)

不言
Release: 2018-08-16 17:01:56
Original
54361 people have browsed it

The content of this article is about the development of WeChat mini program mall to implement the function (code) of adding products to the shopping cart. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. help.

See the effect

Shopping cart.gif

Development plan

1. Put the product information on the product details page Enter the cache
2. Read the cache on the shopping cart page to obtain product information
3. Calculate the shopping cart products and delete the cached products

1. Put the product information into the cache on the product details page

detail.wxml

Copy after login

Bind the bindtap event to add the product to the shopping cart.

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)
    }
  }
Copy after login

2. Read the shopping cart page cache to obtain product information

cart.wxml