3. 商品图片轮播
展示商品的多张图片,支持手动切换。
@Builder CustomSwiper(payload: string[]) {
Stack({ alignContent: Alignment.BottomEnd }) {
Swiper() {
ForEach(payload, (item: string, index: number) => {
Flex({ justifyContent: FlexAlign.Center }) {
Image($rawfile(item))
.height(StyleConstants.FULL_HEIGHT)
.aspectRatio(1)
.objectFit(ImageFit.Cover)
}
.margin({
left: $r('app.float.swiper_image_margin'),
right: $r('app.float.swiper_image_margin'),
top: $r('app.float.vp_twenty'),
bottom: $r('app.float.vp_twenty')
})
}, (item: string) => JSON.stringify(item))
}
.onChange((index: number) => this.swiperIndex = index)
.indicator(false)
.width(StyleConstants.FULL_WIDTH)
.height(StyleConstants.FULL_HEIGHT)
Text(`${this.swiperIndex + 1}/${payload.length}`)
.fontSize($r('app.float.smaller_font_size'))
.fontColor(Color.White)
.textAlign(TextAlign.Center)
.width($r('app.float.swiper_indicator_text_width'))
.height($r('app.float.vp_eighteen'))
.backgroundColor($r('app.color.forty_alpha_black'))
.borderRadius($r('app.float.swiper_indicator_text_radius'))
.margin({
right: $r('app.float.vp_sixteen'),
bottom: $r('app.float.vp_sixteen')
})
}
.width(StyleConstants.FULL_WIDTH)
.backgroundColor(Color.White)
.height($r('app.float.swiper_height'))
}
该代码使用 Swiper 组件实现图片轮播,并显示当前图片的索引。
4. 加入购物车和立即购买功能
处理用户加入购物车和立即购买的操作。
bottomBtnClick(type: FinishType) {
if (this.selectKeys !== undefined) {
this.onSpecificationFinish(type, this.count, this.selectKeys);
}
}
onSpecificationFinish(type: FinishType, count: number, selectKeys: ProductSpecification[]) {
this.count = count;
this.selectKeys = selectKeys;
const params: ShopProps = {
id: getID(),
commodityId: this.info !== undefined ? this.info.id : '',
count,
specifications: this.selectKeys
}
switch (type) {
case FinishType.JOIN_SHOPPING_CART:
this.localDataManager.insertShopCart(params);
promptAction.showToast({
message: $r('app.string.insert_cart_success')
});
break;
case FinishType.BUY_NOW:
if (this.info !== undefined) {
let orderList: Order = {
orderId: params.id,
image: this.info.images[0],
title: this.info.title,
description: this.info.description,
price: this.info.price,
count: params.count,
commodityId: Number.parseInt(params.commodityId),
specifications: this.selectKeys
}
this.pageInfos.pushPath({name: 'ConfirmOrderPage', param: [orderList]})
break;
}
}
}
当用户点击加入购物车或立即购买按钮时,调用 bottomBtnClick 方法,根据用户选择的规格和数量,执行相应的操作。
总结
通过以上代码实现,我们在 HarmonyOS Next 中完成了一个完整的商品详情页。该页面涵盖了商品信息展示、规格选择、用户评价展示、加入购物车和立即购买等功能,同时支持响应式布局,适配不同屏幕尺寸。开发者可以根据实际需求对代码进行扩展和优化,以满足不同应用场景的需求。