小程序商城--将商品加入购物车缓存

本文详细介绍了如何在小程序中实现将商品信息加入到购物车的缓存操作,通过JavaScript代码实现商品数据的存储和读取,确保用户在离开小程序后仍能保留购物车内容。

js代码:

  //添加购物车事件方法
  toCart: function (event) {
    //判断是否选中规格
    this.checkInfo();
    if (!this.data.chooseInfoFlag) {
      wx.showModal({
        title: '提示',
        content: '请选择规格',
        showCancel: false,
        success:{}
      })
    } 

    else {
      //创建动画
      var animation = wx.createAnimation({
        duration: 100,
        timingFunction: 'ease-in-out'
      });
      this.animation = animation;
      animation.translateY(-336).step();
      this.setData({
        animationData: this.animation.export(),
        maskVisual: 'show'
      });
      //将购物车数据添加到缓存
      var that = this
      //获取缓存中的已添加购物车信息
      var cartItems = wx.getStorageSync('cartItems') || []
      console.log(cartItems)
      //判断购物车缓存中是否已存在该货品
      var exist = cartItems.find(function (ele) {
        return ele.id === that.data.goodsInfoId
      })
      console.log(exist)
      if (exist) {
        //如果存在,则增加该货品的购买数量
        exist.quantity = parseInt(exist.quantity) + that.data.buyCount
      } else {
        //如果不存在,传入该货品信息
        cartItems.push({
          id: that.data.goodsInfoId,
          quantity: that.data.buyCount,
          price: that.data.goodsInfoPrice,
          title: that.data.goodsVo.goodsName,
          goodsPicsInfo: that.data.goodsInfoImg
        })
      }
      //加入购物车数据,存入缓存
      wx.setStorage({
        key: 'cartItems',
        data: cartItems,
        success: function (res) {
          //添加购物车的消息提示框
          wx.showToast({
            title: "添加购物车",
            icon: "success",
            durantion: 2000
          })
        }
      })


    }


  }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值