HarmonyOS Next 购物车组件开发实现
概述
在 HarmonyOS Next 应用开发中,购物车功能是电商类应用不可或缺的部分。购物车需要实现商品展示、选择、数量修改、总价计算以及结算等功能。下面将介绍如何构建一个购物车组件,实现商品的管理和结算。
核心代码功能及对应代码段
1. 组件初始化与数据加载
@Component
export struct ShopCart {
@StorageProp('currentBreakpoint') currentBreakpoint: string = 'sm';
@Link @Watch('onListChange') products: Array<Product>;
@State sumPrice: number = 0;
@State isSelectAll: boolean = false;
@State commodityList: Commodity[] = [];
@State @Watch('selectProductChange') selectProducts: SelectProducts[] = [];
@Consume('pageInfo') pageInfo: NavPathStack;
private localDataManager: LocalDataManager = LocalDataManager.instance();
aboutToAppear() {
const sortRes = this.localDataManager.queryCommodityList();
sortRes.sort(() => (Math.random() - StyleConstants.HALF_ONE) > 0 ? 1 : StyleConstants.MINUS_ONE);
this.commodityList = sortRes;
this.onListChange();
}
}
@StorageProp:用于存储当前断点信息,支持响应式布局。@Link和@Watch:绑定商品列表,并在列表变化时触发onListChange方法。aboutToAppear:组件即将显示时,从本地数据管理器中查询商品列表并随机排序,然后调用onListChange方法更新选择状态。
2. 总价计算与商品选择
private countSumPrice() {
this.sumPrice = 0;
this.isSelectAll = this.selectProducts.every((item: SelectProducts) => item.selected);
let tempPrice: number = 0;
this.selectProducts.forEach((item: SelectProducts) => {
if (item.selected) {
let data = this.products.find((value: Product) => value.id === item.key);
const ins = (data !== undefined ? data.price * data.count : 0);
tempPrice += ins;
}
})
this.sumPrice = tempPrice;
}
onListChange() {
this.selectProducts = [];
this.products.forEach((item: Product) => {
let payload: SelectProducts = { selected: false, key: '' };
payload.selected = !!item.selected;
payload.key = item.id;
this.selectProducts.push(payload);
})
this.countSumPrice();
}
countSumPrice:计算选中商品的总价,并判断是否全选。onListChange:更新商品选择状态列表,并调用countSumPrice方法重新计算总价。