demo1984s 的个人博客
本篇为《电商小程序实战》第二篇:购物车功能的实现。
如何计算购物车的总价和管理订单。为了实现购物车功能,我们需要添加一个新的页面:cart 页面。在项目目录中创建以下文件结构:
ecommerce-mini-program/
├── miniprogram/
│ ├── pages/
│ │ ├── cart/
│ │ │ ├── cart.wxml
│ │ │ ├── cart.wxss
│ │ │ ├── cart.js
│ │ │ └── cart.json
│ │ ├── index/
│ │ ├── order/
首先,我们在首页 (index 页面) 中添加购物车功能,点击商品添加到购物车,跳转到购物车页面,展示已选商品。接着,在购物车页面我们可以管理商品的数量,删除商品等操作。
在 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>
接下来,我们在 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;
}
到此为止,我们已经实现了以下功能:
在接下来的篇章中,我们将实现订单提交功能并集成支付接口。主要任务包括:
通过实现这些功能,我们将能够构建一个完整的电商小程序,支持商品展示、购物车管理、订单提交、支付等核心功能。