3. 商品数量处理
对于普通商品,提供加减按钮来更新购物车中商品的数量。点击“+”按钮会调用addCarUtil方法将商品添加到购物车,点击“-”按钮会调用updateMyCarUtil方法更新购物车中商品的数量。
if (this.item?.specType === GoodSpecEnum.NORMAL) {
Row() {
Image($r('app.media.ic_subtract'))
.width(24)
.height(24)
.onClick(() => {
if (this.carGoodInfo?.id && this.carGoodInfo?.num && this.carGoodInfo?.num !== '0') {
updateMyCarUtil(this.carGoodInfo?.id, Number(this.carGoodInfo?.num) - 1)
}
})
.visibility(this.carGoodInfo?.num && this.carGoodInfo?.num !== '0' ? Visibility.Visible :
Visibility.Hidden);
Text(this.carGoodInfo?.num)
.margin({ left: 8, right: 8 })
.fontSize($r('sys.float.Body_M'))
.fontColor($r('sys.color.font_secondary'))
.fontWeight(FontWeight.Medium)
.visibility(this.carGoodInfo?.num && this.carGoodInfo?.num !== '0' ? Visibility.Visible :
Visibility.Hidden);
Image($r('app.media.add_car')).width(24).height(24).onClick(() => {
addCarUtil(this.item)
});
}.padding({ right: 1 });
}
4. 商品规格选择
对于有规格的商品,点击“选择规格”按钮会弹出规格选择面板。用户可以在面板中选择商品规格,选择后会更新商品的单价和总价。点击“加入购物车”按钮会调用addCarSpecUtil方法将商品添加到购物车。
Row() {
Text(this.item?.specType === GoodSpecEnum.PACKAGE_TYPE ? $r('app.string.select_package') :
$r('app.string.select_spec'))
.fontSize($r('sys.float.Caption_M'))
.fontColor($r('sys.color.background_primary'))
.padding({
top: 4,
bottom: 4,
left: 8,
right: 8,
});
}
.borderRadius(14)
.backgroundColor($r('sys.color.multi_color_09'))
.onClick(() => {
if (this.item?.specType === GoodSpecEnum.PACKAGE_TYPE) {
this.goGoodDetail();
return;
}
getGoodInfoUtil(this.item.id).then((resp: Good) => {
this.goodSpecList = resp.spec ?? [];
this.selectSpecArr = this.goodSpecList.map((item: GoodSpec) => {
let goodSpec = item.specVal.find((spec: GoodSpecInfo) => item.specValId === spec.specValNum);
let result: PackageSpec = {
specName: goodSpec?.specValName ?? item.specVal[0].specValName,
specNum: Number(goodSpec?.specValNum ?? 0),
};
return result;
});
getGoodSpecUtil(this.item.id, this.selectSpecArr).then((resp) => {
this.selectSpecInfo = resp;
this.goodSinglePrice = Number(resp.money);
this.sumPrice = new Decimal(this.goodSinglePrice).mul(this.goodNum).toString();
});
this.goodNum = '1'
this.specSheetFlag = true;
});
});
5. 规格选择面板
规格选择面板会展示商品的图片、名称、已选规格和总价,用户可以在面板中选择商品规格和数量。点击“加入购物车”按钮会将商品添加到购物车,并更新必选商品的数量。
Button($r('app.string.add_car'))
.fontSize($r('sys.float.Body_M'))
.fontWeight(FontWeight.Medium)
.fontColor($r('sys.color.font_on_primary'))
.margin(2)
.width(Constants.FULL_SIZE)
.constraintSize({ maxWidth: Constants.FULL_SIZE })
.backgroundColor($r('sys.color.multi_color_09'))
.onClick(() => {
if (!this.selectSpecInfo) {
console.info(`add car empty.`);
return;
}
addCarSpecUtil(this.selectSpecInfo, this.item.id, Number(this.goodNum)).then(() => {
promptAction.showToast({ message: $r('app.string.add_success') });
if (this.selectSpecInfo?.isMust === Constants.GOODS_MUST) {
this.mustGoodsCtrl.addIsMust();
}
this.goodNum = '1';
this.specSheetFlag = false;
});
});
通过以上功能的实现,HarmonyOS 5应用的商品信息组件能够为用户提供良好的商品浏览和购物体验。