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

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

技术栈

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)

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

相关文章
|
自然语言处理 开发者 异构计算
社区供稿 | Llama3-8B中文版!OpenBuddy发布新一代开源中文跨语言模型
此次发布的是在3天时间内,我们对Llama3-8B模型进行首次中文跨语言训练尝试的结果:OpenBuddy-Llama3-8B-v21.1-8k。
|
6月前
|
Kubernetes 安全 开发者
手写 Harness 底层架构: 基于 Deep Agents 深入底层 Sandbox沙盒Infra 基础设施架构
手写 Harness 底层架构: 基于 Deep Agents 深入底层 Sandbox沙盒Infra 基础设施架构
手写 Harness 底层架构: 基于 Deep Agents 深入底层 Sandbox沙盒Infra 基础设施架构
|
5月前
|
人工智能 算法 大数据
年薪$60万赶超ML研究员?拆解Palantir“FDE+Echo”双引擎如何跨越AI落地死亡谷
Palantir“FDE+Echo”双引擎破解AI落地困局:95%试点失败源于旧系统“屎山”与业务脱节。Echo(行业专家)精准定义问题,Delta(FDE工程师)现场构建本体模型、打通脏数据。通过“定制→标准→规模化”飞轮,实现工程工时指数级下降,跨越AI死亡谷。
704 1
|
7月前
|
存储 JSON 前端开发
【前端实战】基于 Vue 3 + Tone.js 构建在线钢琴学习平台
本文介绍基于Vue 3与Tone.js打造的零门槛在线钢琴学习平台,支持键盘演奏、曲目播放/高亮、本地存储与JSON导入导出,纯前端实现、跨平台响应式,星空主题界面美观易用。开源免费,即开即练。
958 2
|
8月前
|
人工智能 自然语言处理 安全
OpenClaw与QQ深度集成:打造智能对话机器人的全链路实践指南
本文以OpenClaw与QQ机器人集成为例,详解AI服务嵌入即时通讯的落地路径:涵盖轻量服务器一键部署、动态端口安全加固、双模式API计费配置、QQ通道对接及闭环验证方法,提供可复用的智能对话系统构建范式。
644 1
|
8月前
|
资源调度 安全 中间件
同创可信与 Anolis OS 完成适配,可信计算 3.0 技术融合再进一步
携手打造“开放、可信、可验证”的国产基础软件生态。
|
人工智能 前端开发 安全
AI 最先替代的开发工作:从重复劳动到人机协同的新范式
AI正加速替代基础开发工作:CRUD页面、样板代码、简单Bug修复、文档生成与基础测试等重复性任务已可通过低代码平台与AI工具高效完成,显著提升生产力。据Gartner报告,70%企业内部系统已采用AI辅助开发,人力投入减少60%-80%。GitHub Copilot等工具更让开发者节省45%编码时间。然而,产品需求分析、系统架构设计、复杂交互体验及创新研发等需深度判断与创造力的工作,仍依赖人类智慧。未来开发者将转型为“AI指挥官”,聚焦问题定义、提示工程与人机协同,核心竞争力转向系统思维、业务理解与技术创新。
1181 15
|
人工智能 小程序 程序员
分享5款实用软件,小众,但棒!
推荐5款小众但超好用的软件:KeyShot(三维渲染)、Sublime Text(文本编辑)、3171.CN(在线AI工具箱)、VideoProc(视频处理)、Everything(文件搜索),功能强大且高效,适合办公与创作,值得收藏使用。
1208 1
|
存储 弹性计算 监控
阿里云国际代理商购买无忧指南:如何省20%成本享专业服务
企业上云虽是数字化转型的必然选择,但高昂成本常让管理者犹豫。通过阿里云国际授权代理商采购,可享最高20%价格优惠及专业支持。文章解析代理商渠道价值、新用户购买指南、采购注意事项及长期成本管理策略,助企业通过正规渠道实现“购买无忧”,享受全生命周期技术支持与价格红利。选对合作伙伴,为未来竞争力投资。
1066 2