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

本文详细介绍了如何在小程序中实现将商品信息加入到购物车的缓存操作,通过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
          })
        }
      })


    }


  }
### 微信小程序实现商品添加到购物车功能 #### 抛物线动画的原理 当用户点击“加入购物车”按钮时,可以利用 CSS 动画模拟物品飞入购物车的效果。此效果基于抛物线运动的数学模型来计算物体移动路径[^2]。 #### 关键代码解析 以下是实现这一功能的关键部分: 1. **HTML 结构** 需要在页面上定义两个主要元素:商品图标和购物车位置。 2. **CSS 动画** 使用 `@keyframes` 定义动画帧,并通过 JavaScript 动态绑定动画类名触发效果。 3. **JavaScript 控制逻辑** 当检测到用户的点击事件后,动态创建一个临时 DOM 元素用于展示飞行轨迹,并启动动画。 #### 示例代码 ```html <!-- WXML --> <view class="product"> <image src="{{productImage}}" bindtap="addToCart"></image> </view> <view class="cart-icon" id="cartIcon"> <!-- 购物车图标 --> <image src="/images/cart.png"></image> </view> ``` ```css /* WXSS */ .product { position: relative; } .fly-animation { width: 50px; height: 50px; position: absolute; animation: flyToCart 1s ease-in-out forwards; } @keyframes flyToCart { from { transform: translateX(0); } to { /* 计算目标坐标并设置最终位置 */ transform: translate(-50%, -50%); } } ``` ```javascript // JS 文件 Page({ addToCart(e) { const productImage = e.currentTarget.dataset.image; // 获取当前商品图片 const cartPosition = this.getCartPosition(); // 获取购物车的位置 // 创建虚拟节点作为动画载体 const tempNode = document.createElement('div'); tempNode.style.position = 'absolute'; tempNode.style.width = '50px'; tempNode.style.height = '50px'; tempNode.style.backgroundImage = `url(${productImage})`; // 将其附加至 body 并立即移除 document.body.appendChild(tempNode); setTimeout(() => { tempNode.remove(); }, 1000); // 动画持续时间应与此一致 // 设置初始样式与动画 Object.assign(tempNode.style, { top: `${e.touches[0].clientY}px`, left: `${e.touches[0].clientX}px`, zIndex: 999, transitionProperty: 'transform', transitionDuration: '1s' }); requestAnimationFrame(() => { // 确保更新完成后再应用变换 Object.assign(tempNode.style, { transform: `translate(${cartPosition.x}px, ${cartPosition.y}px)` }); }); }, getCartPosition() { const query = wx.createSelectorQuery(); return new Promise((resolve) => { query.select('#cartIcon').boundingClientRect(rect => resolve(rect)).exec(); }); } }); ``` 以上代码实现了从商品图标的触碰点出发,沿着一条曲线进入购物车区域的视觉效果。 --- #### 数据存储与管理 为了记录已选中商品数量以及总价等信息,在实际开发中还需要维护本地缓存或者数据库同步状态。可以通过调用微信 API 的 `wx.setStorageSync()` 方法保存数据[^1]。 例如: ```javascript const updateLocalStorage = (productId) => { let cartItems = wx.getStorageSync('cart') || {}; if (!cartItems[productId]) { cartItems[productId] = { count: 1 }; } else { cartItems[productId].count += 1; } wx.setStorageSync('cart', cartItems); }; ``` 每次成功执行上述方法之后即可刷新界面显示最新的购物车内项目数。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值