Harmonyos5应用开发实战——商品信息组件实现
文章内容概要
本文聚焦于HarmonyOS 5应用开发中商品信息组件的实现。详细介绍了该组件如何展示商品信息、处理商品数量变化、处理商品规格选择以及将商品添加到购物车等核心功能,同时阐述了组件与购物车数据的交互逻辑。
核心功能介绍
1. 组件初始化与数据监听
在组件即将显示时,调用aboutToAppear方法,该方法会触发myCarChange方法,用于监听购物车数据的变化,并查找当前商品在购物车中的信息。
aboutToAppear(): void {
this.myCarChange();
}
myCarChange() {
this.carGoodInfo = this.myCar.res?.find((item: CarGoodInfo) => item.goodId === this.item.id);
console.info(`carGoodInfo: ${JSON.stringify(this.carGoodInfo)}.`);
}
2. 商品信息展示
组件会展示商品的图片、名称、内容、销量和价格等信息。当商品名称过长时,会隐藏商品内容以节省空间。
Image(`${CommonUrl.CLOUD_STORAGE_URL}${this.item?.logo}`).width(82).height(82).borderRadius(8).onClick(() => {
this.goGoodDetail();
});
Column() {
Column() {
Text(this.item?.name)
.fontSize($r('sys.float.Body_M'))
.fontWeight(FontWeight.Medium)
.fontColor($r('sys.color.font_primary'))
.maxLines(2)
.textOverflow({ overflow: TextOverflow.Ellipsis });
if (this.showGoodContent) {
Text(this.item?.content)
.fontSize($r('sys.float.Caption_M'))
.lineHeight(14)
.fontColor($r('sys.color.font_secondary'))
.margin({ top: 2 })
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis });
}
Text(Number(this.item?.sales) > 100 ? $r('app.string.sales_more') :
$r('app.string.month_sale', this.item?.sales))
.fontSize($r('sys.float.Caption_M'))
.lineHeight(14)
.fontColor($r('sys.color.font_secondary'))
.margin({ top: 2 });
}.alignItems(HorizontalAlign.Start).onClick(() => {
this.goGoodDetail();
});