《仿盒马》app开发技术分享-- 购物车业务逻辑完善(34)

2025-06-25 11:45:34
106次阅读
0个评论

技术栈

Appgallery connect

开发准备

之前我们已经实现了购物车相关的内容,实现了购物车数据列表的展示,但是我们结算订单之后我们的购物车列表并没有刷新,而且底部的状态栏并没有明显的数据展示来提醒用户,而且当我们在商品详情页添加新商品,底部也没有同步更新,这一节我们要解决的问题就是这些

功能分析

1.新增商品 新增商品时我们需要在底部展示一个当前商品数量的标记展示在购物车图标的右上角 2.提交购物车商品列表 当我们提交购物车商品列表时,我们需要同步刷新购物车右上角数量展示,以及购物车列表页面的数据更新 3.购物车商品删除 当购物车商品滑动删除时,刷新列表页面的列表,以及更新底部状态栏的商品数量展示

代码实现

首先在底部购物车图标右上角新增Badge组件

 @Builder tabBuilder(title: string, targetIndex: number, selectedImg: Resource, normalImg: Resource) {
    Column() {
      if (targetIndex==2){
        Badge({
          count: this.badgeCount,
          style: { badgeSize: 14, badgeColor: '#FA2A2D'},
          position: BadgePosition.RightTop,
        })
        {
          Image(this.currentIndex === targetIndex ? selectedImg : normalImg)
            .width(30)
            .height(30)
        }
      }else {
        Image(this.currentIndex === targetIndex ? selectedImg : normalImg)
          .width(this.isCheck_Index_One&&targetIndex===0?50:25)
          .height(this.isCheck_Index_One&&targetIndex===0?50:25)
          .borderRadius(this.isCheck_Index_One&&targetIndex===0?25:0)
      }
      Text(title)
        .fontSize(14)
        .margin({top:5})
        .fontWeight(this.currentIndex === targetIndex ?FontWeight.Bold:FontWeight.Normal)
        .fontColor(this.currentIndex === targetIndex ? '#fff65753' : '#6B6B6B')
    }
    .width('100%')
    .height(50)
    .justifyContent(FlexAlign.Center)
  }

然后我们在购物车组件内新增一个控制刷新的变量,并监听变量是否修改,修改后我们执行云数据库的查询方法,查询当前登录用户的购物车列表,当提交完订单之后,我们在订单提交页通过emitter传递状态

订单提交

        Text("提交订单")
          .fontColor(Color.White)
          .padding(10)
          .borderRadius(10)
          .backgroundColor("#d81e06")
          .fontSize(14)
          .onClick(async ()=>{
            if (this.addressInfo!=null) {
              let databaseZone = cloudDatabase.zone('default');
              try {
                for (let i = 0; i < this.productList.length; i++) {
                  let productPush = new order_product_list();
                  productPush.id=this.codeId+i
                  productPush.order_product_id=this.codeId
                  productPush.img=this.productList[i].productImgAddress
                  productPush.price=this.productList[i].productPrice
                  productPush.name=this.productList[i].productName
                  productPush.originalPrice=this.productList[i].productOriginalPrice
                  productPush.spec=this.productList[i].productSpecName
                  productPush.buyAmount=this.productList[i].buyAmount
                  let num = await databaseZone.upsert(productPush);
                  hilog.info(0x0000, 'testTag', `Succeeded in upserting data, result: ${num}`);

                }
              }catch (e) {
                hilog.info(0x0000, 'testTag', `Succeeded in upserting data, result: ${e}`);
              }


              let orderPush = new order_list();
              orderPush.id=Math.floor(Math.random() * 1000000)
              orderPush.user_id=this.user!.user_id
              orderPush.order_product_id=String(this.codeId)
              orderPush.order_code=this.generateOrderNo(10)
              orderPush.order_status=0
              if (this.remark!='') {
                orderPush.order_remark=this.remark
              }
              orderPush.address=this.addressInfo.address
              orderPush.nickname=this.addressInfo.nikeName
              orderPush.phone=this.addressInfo.phone
              orderPush.order_create_time=this.formatCurrentDate()
              orderPush.order_pay_time=this.formatCurrentDate()
              let num = await databaseZone.upsert(orderPush);
              hilog.info(0x0000, 'testTag', `Succeeded in upserting data, result: ${num}`);
              if (num>0) {


                for (let i = 0; i < this.productList.length; i++) {
                  if (this.productList[i].isNeedPay) {
                    let item = new cart_product_list();
                    item.id=this.productList[i].id
                    let listData = await databaseZone.delete(item);
                    hilog.info(0x0000, 'testTag', `Succeeded in upserting data, result: ${listData}`);
                  }
                }
                let eventData: emitter.EventData = {
                  data: {}
                };
                let innerEvent: emitter.InnerEvent = {
                  eventId: 1012,
                  priority: emitter.EventPriority.HIGH
                };
                emitter.emit(innerEvent, eventData);

                  router.replaceUrl({url:'pages/view/OrderSuccessPage',params:orderPush})
              }
            } else {
              showToast("请先选择地址")
            }
          })

购物车页

@Link @Watch("onListRefresh") listRefresh:boolean
  async onListRefresh(){
    const  userInfo= await StorageUtils.getAll('user')
    if (userInfo!=null) {
      this.user=JSON.parse(userInfo)
    }
    if (this.currentIndexCheck==this.currentIndex) {
      let condition = new cloudDatabase.DatabaseQuery(cart_product_list);
      condition.equalTo("user_id",this.user?.user_id)
      let listData = await databaseZone.query(condition);
      let json = JSON.stringify(listData)
      this.productList= JSON.parse(json)
      hilog.info(0x0000, 'testTag', `Succeeded in upserting data, result: ${listData}`);
      this.getCountPrice()
      this.flag=true
    }
  }

首页接收

@State listRefresh:boolean=false

 let innerEvent1: emitter.InnerEvent = {
      eventId: 1012
    };

    let callback1: Callback<emitter.EventData> = async (eventData: emitter.EventData) => {
      this.listRefresh=true
      let databaseZone = cloudDatabase.zone('default');
      let condition = new cloudDatabase.DatabaseQuery(cart_product_list);
      condition.equalTo("user_id",this.user?.user_id)
      let listData = await databaseZone.query(condition);
      this.badgeCount=listData.length
    }
    emitter.on(innerEvent1, callback1);

新增商品

 Row(){
      Text("加入购物车")
        .width('70%')
        .borderRadius(30)
        .textAlign(TextAlign.Center)
        .fontColor(Color.Black)
        .margin({top:70})
        .height(40)
        .fontSize(18)
        .fontWeight(FontWeight.Bold)
        .backgroundColor("#FCDB29")
        .onClick(async ()=>{
          try {

            let databaseZone = cloudDatabase.zone('default');
            let condition = new cloudDatabase.DatabaseQuery(cart_product_list);
            condition.equalTo("productId",this.product?.id).and().equalTo("productSpecId",this.specList[this.checkIndex].id)
            let listData = await databaseZone.query(condition);
            let json = JSON.stringify(listData)
            hilog.info(0x0000, 'testTag', `Succeeded in upserting data, result: ${json}`);
           let request:CartProductList[]=JSON.parse(json)
            let cartPush = new cart_product_list();

            if (request.length>0) {
              let data:CartProductList=request[0]
              cartPush.id=data.id;
              cartPush.productId=data.productId//商品id
              cartPush.productSpecId=data.productSpecId//规格id
              cartPush.productName=data.productName//商品名称
              cartPush.productSpecName=data.productSpecName
              cartPush.productImgAddress=data.productImgAddress
              cartPush.buyAmount=this.addNumber+data.buyAmount//商品数量
              cartPush.isNeedPay=data.isNeedPay//是否选中 默认为true
              cartPush.activityType=data.activityType//活动类型 暂无
              cartPush.productPrice=data.productPrice//价格
              cartPush.productOriginalPrice=data.productOriginalPrice//划线价
              cartPush.couponPrice=data.couponPrice
            }else {

              cartPush.id=Math.floor(Math.random() * 1000000);
              cartPush.productId=this.product!.id//商品id
              cartPush.productSpecId=this.specList[this.checkIndex].id//规格id
              cartPush.productName=this.product!.name//商品名称
              cartPush.productSpecName=this.specList[this.checkIndex].name
              cartPush.productImgAddress=this.product!.url//图片地址
              cartPush.buyAmount=this.addNumber//商品数量
              cartPush.isNeedPay=true//是否选中 默认为true
              cartPush.activityType="1"//活动类型 暂无
              cartPush.productPrice=this.product!.price//价格
              cartPush.productOriginalPrice=this.product!.original_price//划线价
              cartPush.couponPrice=0
              cartPush.user_id=this.user!.user_id
            }
            let num = await databaseZone.upsert(cartPush);
            hilog.info(0x0000, 'testTag', `Succeeded in upserting data, result: ${num}`);
            if (num>0) {
              showToast("添加商品成功")


            }
            let eventData: emitter.EventData = {
              data: {}
            };

            let innerEvent: emitter.InnerEvent = {
              eventId: 1011,
              priority: emitter.EventPriority.HIGH
            };

            emitter.emit(innerEvent, eventData);
            this.controller.close()
          }catch (err) {
            hilog.info(0x0000, 'testTag', `Succeeded in upserting data, result: ${err}`);

          }


        })
    }
    .width('100%')
    .justifyContent(FlexAlign.Center)

到这里我们的业务逻辑就实现了

收藏00

登录 后评论。没有帐号? 注册 一个。