第13章:构建一个电商App(简化版)
购物车功能
1. 功能需求分析
购物车是电商App的核心模块之一,主要功能包括:
- 商品管理:添加/删除商品、修改商品数量
- 实时计算:总价自动更新(含优惠计算)
- 状态同步:与商品详情页、订单页数据联动
- 本地缓存:未登录用户暂存数据
2. 数据结构设计
// 购物车单项类型
interface CartItem {
id: string; // 商品唯一ID
name: string; // 商品名称
price: number; // 单价
count: number; // 数量
selected: boolean; // 是否选中
image: string; // 缩略图URL
}
// 购物车全局状态
class CartState {
items: CartItem[] = [];
promotions: Promotion[] = []; // 优惠活动
}
3. 核心功能实现
3.1 添加商品逻辑
function addToCart(item: Product) {
const existingItem = this.cartState.items.find(i => i.id === item.id);
if (existingItem) {
existingItem.count += 1;
} else {
this.cartState.items.push({
...item,
count: 1,
selected: true
});
}
saveToLocalStorage();
}
3.2 数量修改组件
@Component
struct Counter {
@Link count: number;
build() {
Row() {
Button('-')
.onClick(() => this.count > 1 && this.count--)
Text(this.count.toString())
.width(40)
Button('+')
.onClick(() => this.count++)
}
}
}
3.3 总价计算
function calculateTotal() {
return this.cartState.items
.filter(item => item.selected)
.reduce((sum, item) => sum + item.price * item.count, 0);
}
4. 关键UI实现
4.1 购物车列表
@Component
struct CartList {
@State cartItems: CartItem[] = [];
build() {
List() {
ForEach(this.cartItems, item => {
ListItem() {
CartItemCard({ item: item })
}
})
}
.onDelete((index: number) => this.deleteItem(index))
}
}
4.2 底部结算栏
@Component
struct CheckoutBar {
@State total: number = 0;
build() {
Row() {
Text(`合计:¥${this.total.toFixed(2)}`)
.fontSize(18)
Button('去结算')
.onClick(() => router.push('checkout'))
}
.justifyContent(FlexAlign.SpaceBetween)
}
}
5. 高级功能实现
5.1 本地持久化
// 使用AppStorage实现自动持久化
AppStorage.SetOrCreate('cartData', []);
@Watch('cartState.items')
function onCartChange() {
AppStorage.Set('cartData', this.cartState.items);
}
5.2 优惠券系统集成
function applyCoupon(code: string) {
const coupon = fetchCouponFromServer(code);
if (coupon.valid) {
this.cartState.promotions.push({
type: 'COUPON',
discount: coupon.discount
});
}
}
6. 常见问题解决方案
数据同步问题:
- 使用@Observed装饰器实现商品详情页和购物车的双向同步
- 商品下架时自动移出购物车
性能优化:
- 大数据量时使用LazyForEach懒加载
- 防抖处理频繁的数量修改操作
多端适配:
- 根据设备类型调整显示列数(手机/平板)
- 横竖屏切换时重组布局
