HarmonyOS Next 商品详情页与订单确认功能开发(一)

136 阅读1分钟

HarmonyOS Next 商品详情页与订单确认功能开发

概述

在 HarmonyOS Next 应用开发中,构建商品详情页并实现订单确认功能是电商类应用的常见需求。下面将介绍如何开发一个具备商品展示、规格选择、用户评价显示、加入购物车和立即购买等功能的商品详情页,并能顺利跳转到订单确认页面。

核心代码功能及对应代码段

1. 页面初始化与数据获取

在页面即将显示时,通过 localDataManager 获取商品信息,并初始化商品规格选择。同时,获取用户当前位置。

aboutToAppear() {
  this.info = this.localDataManager.queryCommodityListById(this.commodityId);
  if (this.info.specifications !== undefined) {
    this.info.specifications.forEach((item: Specification) => {
      if (this.selectKeys !== undefined) {
        let specificationData:ProductSpecification = new ProductSpecification()
        specificationData.name = item.title;
        specificationData.value = item.data[0].key;
        this.selectKeys.push(specificationData)
      }
    });
  }
  getCurrentLocation(getContext(this) as common.UIAbilityContext, (location: geoLocationManager.Location) => {
    if (location) {
      const req:geoLocationManager.ReverseGeoCodeRequest = {"latitude": location.latitude, "longitude": location.longitude, "maxItems": 1};
      geoLocationManager.getAddressesFromLocation(req).then((data) => {
        this.location = data[0].placeName || ''
      })
    }
  })
}
2. 规格选择对话框

提供一个对话框让用户选择商品规格,选择完成后根据用户操作执行加入购物车或立即购买。

dialogController: CustomDialogController = new CustomDialogController({
  builder: SpecificationDialog({
    onFinish: (type: FinishType, count: number, selectKeys: ProductSpecification[]): void =>
      this.onSpecificationFinish(type, count, selectKeys),
    data: $info,
    count: $count,
    selectTags: $selectKeys,
    productOptions:$productOptions
  }),
  autoCancel: true,
  alignment: DialogAlignment.Bottom,
  customStyle: true
})

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;
      }
  }
}