demo1984s 的个人博客 demo1984s 的个人博客

记录精彩的程序人生

目录
电商小程序实战02·购物车功能的实现
/  

电商小程序实战02·购物车功能的实现

前言

本篇为《电商小程序实战》第二篇:购物车功能的实现。

  • 内容简介:重点实现购物车功能。
  • 主要内容:
    • 如何使用 wx.setStorage 和 wx.getStorage 来存储和读取购物车数据。
    • 如何在小程序面中处理商品数量的增加、减少和删除。`
    • 如何计算购物车的总价和管理订单。
  • 目标:我们将通过实现商品的添加、删除、修改数量等功能,掌握本地存储(wx.setStorage 和 wx.getStorage)的使用。

    项目目录结构更新

为了实现购物车功能,我们需要添加一个新的页面:cart 页面。在项目目录中创建以下文件结构:

ecommerce-mini-program/
├── miniprogram/
│   ├── pages/
│   │   ├── cart/
│   │   │   ├── cart.wxml
│   │   │   ├── cart.wxss
│   │   │   ├── cart.js
│   │   │   └── cart.json
│   │   ├── index/
│   │   ├── order/

商品列表与购物车的交互

首先,我们在首页 (index 页面) 中添加购物车功能,点击商品添加到购物车,跳转到购物车页面,展示已选商品。接着,在购物车页面我们可以管理商品的数量,删除商品等操作。

修改首页 index.wxml,添加添加到购物车按钮

在 index.wxml 中,我们为每个商品添加一个 “加入购物车” 按钮。修改后的代码如下:

<!-- index.wxml -->
<view class="container">
  <!-- 商品轮播图 -->
  <swiper class="swiper-container" autoplay="true" interval="3000" circular="true">
    <swiper-item wx:for="{{banner}}" wx:key="index">
      <image class="swiper-image" src="{{item.imageUrl}}" mode="aspectFill"></image>
    </swiper-item>
  </swiper>

  <!-- 商品列表 -->
  <view class="product-list">
    <view class="product-item" wx:for="{{products}}" wx:key="index">
      <image class="product-image" src="{{item.imageUrl}}" mode="aspectFill"></image>
      <view class="product-info">
        <text class="product-name">{{item.name}}</text>
        <text class="product-price">{{item.price}}元</text>
      </view>
      <!-- 加入购物车按钮 -->
      <button class="add-to-cart" bindtap="addToCart" data-product="{{item}}">加入购物车</button>
    </view>
  </view>

  <!-- 跳转到购物车 -->
  <button class="go-cart" bindtap="goToCart">查看购物车</button>
</view>
  • 我们为每个商品添加了一个 加入购物车 按钮。
  • 使用 bindtap 事件绑定点击事件,并传递商品信息。

    在 index.js 中实现购物车功能

接下来,我们在 index.js 中实现 addToCart 和 goToCart 方法:

// index.js
Page({
  data: {
    banner: [
      { imageUrl: 'https://example.com/banner1.jpg' },
      { imageUrl: 'https://example.com/banner2.jpg' },
      { imageUrl: 'https://example.com/banner3.jpg' }
    ],
    products: [
      { id: 1, name: '商品1', price: 99, imageUrl: 'https://example.com/product1.jpg' },
      { id: 2, name: '商品2', price: 199, imageUrl: 'https://example.com/product2.jpg' },
      { id: 3, name: '商品3', price: 299, imageUrl: 'https://example.com/product3.jpg' },
      { id: 4, name: '商品4', price: 399, imageUrl: 'https://example.com/product4.jpg' }
    ]
  },

  // 添加商品到购物车
  addToCart: function (e) {
    let product = e.currentTarget.dataset.product; // 获取点击的商品信息
    let cart = wx.getStorageSync('cart') || []; // 获取本地缓存的购物车数据,如果没有则初始化为空数组
    
    // 检查商品是否已在购物车中
    let index = cart.findIndex(item => item.id === product.id);
    if (index === -1) {
      // 如果商品不在购物车中,添加该商品
      product.quantity = 1;
      cart.push(product);
    } else {
      // 如果商品已在购物车中,增加数量
      cart[index].quantity += 1;
    }

    // 更新本地缓存
    wx.setStorageSync('cart', cart);
    wx.showToast({
      title: '已加入购物车',
      icon: 'success'
    });
  },

  // 跳转到购物车页面
  goToCart: function () {
    wx.navigateTo({
      url: '/pages/cart/cart'
    });
  }
});
  • addToCart 方法:点击商品时将商品添加到购物车,若商品已存在,则增加数量。
  • goToCart 方法:跳转到购物车页面。

    创建购物车页面

在 cart.wxml 中,我们展示购物车中的商品,允许用户修改商品数量或者删除商品。

<!-- cart.wxml -->
<view class="cart-container">
  <view wx:for="{{cart}}" wx:key="id" class="cart-item">
    <image class="product-image" src="{{item.imageUrl}}" mode="aspectFill"></image>
    <view class="cart-info">
      <text class="product-name">{{item.name}}</text>
      <text class="product-price">{{item.price}}元</text>
      <view class="quantity-controls">
        <button bindtap="decreaseQuantity" data-id="{{item.id}}">-</button>
        <text class="quantity">{{item.quantity}}</text>
        <button bindtap="increaseQuantity" data-id="{{item.id}}">+</button>
      </view>
      <button class="remove-item" bindtap="removeItem" data-id="{{item.id}}">删除</button>
    </view>
  </view>
  
  <!-- 总计 -->
  <view class="cart-total">
    <text>总价:{{totalPrice}}元</text>
  </view>
  <!-- 提交订单按钮 -->
  <button class="submit-order" bindtap="submitOrder">提交订单</button>
</view>

在 cart.js 中,我们实现购物车的功能:商品数量增加、减少、删除,和计算总价。

// cart.js
Page({
  data: {
    cart: [],
    totalPrice: 0
  },

  // 页面加载时获取购物车数据
  onLoad: function () {
    let cart = wx.getStorageSync('cart') || [];
    this.setData({
      cart: cart
    });
    this.calculateTotalPrice();
  },

  // 增加商品数量
  increaseQuantity: function (e) {
    let id = e.currentTarget.dataset.id;
    let cart = this.data.cart;
    let index = cart.findIndex(item => item.id === id);
    if (index !== -1) {
      cart[index].quantity += 1;
      this.setData({ cart: cart });
      wx.setStorageSync('cart', cart);
      this.calculateTotalPrice();
    }
  },

  // 减少商品数量
  decreaseQuantity: function (e) {
    let id = e.currentTarget.dataset.id;
    let cart = this.data.cart;
    let index = cart.findIndex(item => item.id === id);
    if (index !== -1 && cart[index].quantity > 1) {
      cart[index].quantity -= 1;
      this.setData({ cart: cart });
      wx.setStorageSync('cart', cart);
      this.calculateTotalPrice();
    }
  },

  // 删除商品
  removeItem: function (e) {
    let id = e.currentTarget.dataset.id;
    let cart = this.data.cart.filter(item => item.id !== id);
    this.setData({ cart: cart });
    wx.setStorageSync('cart', cart);
    this.calculateTotalPrice();
  },

  // 计算总价
  calculateTotalPrice: function () {
    let totalPrice = 0;
    this.data.cart.forEach(item => {
      totalPrice += item.price * item.quantity;
    });
    this.setData({ totalPrice: totalPrice });
  },

  // 提交订单
  submitOrder: function () {
    if (this.data.cart.length === 0) {
      wx.showToast({
        title: '购物车为空',
        icon: 'none'
      });
      return;
    }
    // 跳转到订单页面
    wx.navigateTo({
      url: '/pages/order/order'
    });
  }
});

更新购物车页面样式

在 cart.wxss 中,我们设置购物车页面的基本样式:

/* cart.wxss */
.cart-container {
  padding: 20px;
}

.cart-item {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
}

.product-image {
  width: 80px;
  height: 80px;
  margin-right: 15px;
}

.cart-info {
  flex: 1;
}

.product-name {
  font-size: 16px;
  font-weight: bold;
}

.product-price {
  font-size: 14px;
  color: #ff6600;
}

.quantity-controls {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.quantity-controls button {
  width: 30px;
  height: 30px;
  font-size: 20px;
  background-color: #f5f5f5;
  border: 1px solid #ccc;
  text-align: center;
}

.quantity {
  margin: 0 10px;
  font-size: 16px;
}

.remove-item {
  margin-top: 10px;
  color: red;
  background: none;
  border: none;
  font-size: 14px;
  cursor: pointer;
}

.cart-total {
  margin-top: 20px;
  font-size: 18px;
  font-weight: bold;
  text-align: right;
}

.submit-order {
  width: 100%;
  padding: 15px;
  margin-top: 20px;
  background-color: #ff6600;
  color: white;
  font-size: 16px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

小结

到此为止,我们已经实现了以下功能:

  1. 首页商品展示:展示商品列表,支持点击商品加入购物车。
  2. 购物车管理:
    • 在购物车页面,展示购物车中的商品。
    • 支持增加和减少商品数量。
    • 支持删除购物车中的商品。
    • 动态计算购物车总价。
  3. 本地存储:通过微信小程序的 wx.setStorage 和 wx.getStorage 来存储购物车数据,确保数据持久化。

下一步

在接下来的篇章中,我们将实现订单提交功能并集成支付接口。主要任务包括:

  • 提交购物车商品,生成订单。
  • 选择收货地址。
  • 集成微信支付功能,处理支付流程。

通过实现这些功能,我们将能够构建一个完整的电商小程序,支持商品展示、购物车管理、订单提交、支付等核心功能。