Harmonyos5应用开发实战——商品详情页功能实现(part2)

110 阅读1分钟
3. 商品规格选择与总价计算

用户选择商品规格时,会调用getGoodSpecUtil函数获取新的规格信息,并更新商品单价和总价。

.onClick(() => {
  if (this.selectSpecArr && this.selectSpecArr[index]) {
    let pkgSpec: PackageSpec = {
      specName: item.specValName,
      specNum: Number(item.specValNum),
    };
    this.selectSpecArr[index] = pkgSpec;
    getGoodSpecUtil(this.goodInfo?.id, this.selectSpecArr).then((resp) => {
      this.selectSpecInfo = resp;
      this.goodSinglePrice = Number(resp.money);
      this.sumPrice = `${this.goodSinglePrice * Number(this.goodNum)}`;
    });
  }
});
4. 商品数量调整与总价更新

通过点击加减按钮,用户可以调整商品数量,同时总价会根据新的数量进行更新。

Image($r('app.media.ic_subtract')).width(24).onClick(() => {
  if (Number(this.goodNum) > 1) {
    this.goodNum = `${Number(this.goodNum) - 1}`;
    this.sumPrice = new Decimal(this.goodSinglePrice).mul(this.goodNum).toString();
  }
});
Image($r('app.media.add_car')).width(24).onClick(() => {
  this.goodNum = `${Number(this.goodNum) + 1}`;
  this.sumPrice = new Decimal(this.goodSinglePrice).mul(this.goodNum).toString();
});
5. 加入购物车功能

点击“加入购物车”按钮,根据商品是否有规格,调用不同的函数将商品加入购物车。若加入成功,会显示提示信息并更新必选商品数量。

clickAddCar() {
  if (this.goodSpecList.length) {
    if (!this.selectSpecInfo) {
      console.error(`add car selectSpecInfo empty.`);
      return;
    }
    addCarSpecUtil(this.selectSpecInfo, this.goodInfo?.id ?? '', Number(this.goodNum)).then(() => {
      promptAction.showToast({ message: $r('app.string.add_success') });
      if (this.goodInfo?.isMust === Constants.GOODS_MUST) {
        this.mustGoodsCtrl.addIsMust(Number(this.goodNum));
      }
      this.pageStack.pop();
    }).catch(() => {
      promptAction.showToast({ message: $r('app.string.add_failed') });
    });
  } else {
    if (this.goodInfo) {
      addCarUtil(this.goodInfo, Number(this.goodNum)).then(() => {
        promptAction.showToast({ message: $r('app.string.add_success') });
        if (this.goodInfo?.isMust === Constants.GOODS_MUST) {
          this.mustGoodsCtrl.addIsMust(Number(this.goodNum));
        }
        this.pageStack.pop();
      }).catch(() => {
        promptAction.showToast({ message: $r('app.string.add_failed') });
      });
    } else {
      console.error(`add car goodInfo empty.`);
    }
  }
}

通过以上功能的实现,HarmonyOS 5应用的商品详情页能够为用户提供良好的商品浏览和购物体验。