HarmonyOS NEXT星河版之美团外卖点餐功能实战(下)

文章目录

    • 一、购物车逻辑
      • 1.1 购物车及加减菜
      • 1.2 菜品的加减---方案一
      • 1.3 菜品的加减---方案二
      • 1.4 购物车View完善
      • 1.5 清空购物车
      • 1.5 购物车数量和价格
    • 二、小结

一、购物车逻辑

1.1 购物车及加减菜

utils目录下新建CartStore.ets文件,如下:

import { FoodItem } from '../models'

// 本地持久化购物车数据
PersistentStorage.persistProp<FoodItem[]>('cartStore', [])

export class CartStore {

  static getCarts() {
    return AppStorage.get<FoodItem[]>('cartStore') || [] as FoodItem[]
  }

  /**
   * 加菜or减菜
   * @param foodItem
   * @param type
   */
  static addOrCutFood(foodItem: FoodItem, type: 'add' | 'cut') {
    const cartList = CartStore.getCarts()
    const item = cartList.find((item) => item.id === foodItem.id)
    // 加菜
    if (type === 'add') {
      if (item) {
        item.count++
      } else {
        foodItem.count = 1
        cartList.unshift(foodItem)
      }
    } else { // 减菜
      if (item && item.count > 0) {
        item.count--
        if (item.count === 0) {
          const index = cartList.findIndex((item) => item.id === foodItem.id)
          cartList.splice(index, 1)
        }
      }
    }
    AppStorage.set<FoodItem[]>('cartStore', [...cartList])
  }
}

1.2 菜品的加减—方案一

实现如下效果,当选择数量大于0时展示-及数量
在这里插入图片描述
改造MTAddCutView,如下:

import { FoodItem } from '../models'
import { CartStore } from '../utils/CartStore'

@Preview
@Component
export struct MTAddCutView {
  // 当前菜品
  @Require @Prop foodItem: FoodItem = new FoodItem()
  // 购物车数据
  @Consume cartList: FoodItem[]

  // 当前选择数量
  getCount() {
    return this.cartList.find(obj => obj.id === this.foodItem.id)?.count || 0
  }

  build() {
    Row({ space: 8 }) {
      Row() {
        Image($r('app.media.ic_screenshot_line'))
          .width(10)
          .aspectRatio(1)
      }
      .width(16)
      .height(16)
      .justifyContent(FlexAlign.Center)
      .backgroundColor(Color.White)
      .borderRadius(4)
      .border({
        color: $r('app.color.main_color'),
        width: 0.5
      })
      // 如果为0,则取消展示
      .visibility(this.getCount() > 0 ? Visibility.Visible : Visibility.Hidden)
      // 减少菜品
      .onClick(() => {
        CartStore.addOrCutFood(this.foodItem, 'cut')
      })

      Text(this.getCount().toString())
        .fontSize(14)
        .visibility(this.getCount() > 0 ? Visibility.Visible : Visibility.Hidden)

      Row() {
        Image($r('app.media.ic_public_add_filled'))
          .width(10)
          .aspectRatio(1)
      }
      .width(16)
      .height(16)
      .justifyContent(FlexAlign.Center)
      .borderRadius(4)
      .backgroundColor($r('app.color.main_color'))
      // 添加菜品
      .onClick(() => {
        CartStore.addOrCutFood(this.foodItem, 'add')
      })
    }

  }
}

在主页面MeiTuanPage.ets中,通过WatchStorageProp实现数据动态展示:

// 方案一:使用StorageProp和Watch实现
@StorageProp('cartStore') @Watch('onCartChange') cartData: FoodItem[] = []
// 购物车数据变化发生回调
onCartChange() {
  this.cartList = CartStore.getCarts()
}

1.3 菜品的加减—方案二

使用事件总线实现事件的发布和订阅。
CartStore.ets中增加事件发布:

...
 AppStorage.set<FoodItem[]>('cartStore', [...cartList])
// 方案二:使用事件总线
getContext().eventHub.emit('changeCart')
...

MeiTuanPage.ets中注册订阅:

aboutToAppear(): void {
  this.categoryList = mockCategory
  this.cartList = CartStore.getCarts()
  // 方案二:使用事件总线
  getContext().eventHub.on('changeCart', () => {
    this.cartList = CartStore.getCarts()
  })
}

1.4 购物车View完善

购物车展示真实数据及加减菜品:
MTCartView

import { FoodItem } from '../models'
import { MTCartItemView } from './MTCartItemView'

@Preview
@Component
export struct MTCartView {
  @Consume cartList: FoodItem[]

  build() {
    Column() {
      Column() {
        // 头部
        Row() {
          Text('购物车')
            .fontSize(14)
          Text('清空购物车')
            .fontColor($r('app.color.search_font_color'))
            .fontSize(12)
        }
        .width('100%')
        .height(48)
        .justifyContent(FlexAlign.SpaceBetween)
        .padding({ left: 15, right: 15 })

        // 购物车列表
        List() {
          ForEach(this.cartList, (item: FoodItem) => {
            ListItem() {
              MTCartItemView({ foodItem: item })
            }
          })
        }
        .divider({ strokeWidth: 1, color: '#e5e5e5', startMargin: 20, endMargin: 20 })
      }
      .backgroundColor(Color.White)
      .padding({
        bottom: 88
      })
      .borderRadius({
        topLeft: 12,
        topRight: 12
      })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.End)
    .backgroundColor('rgba(0,0,0,0.5)')

  }
}

MTCartItemView

import { FoodItem } from '../models'
import { MTAddCutView } from './MTAddCutView'

@Preview
@Component
export struct MTCartItemView {
  foodItem: FoodItem = new FoodItem()

  build() {
    Row({ space: 6 }) {
      Image('https://bkimg.cdn.bcebos.com/pic/4d086e061d950a7bc94a331704d162d9f3d3c9e2')
        .width(42)
        .aspectRatio(1)
        .borderRadius(5)
      Column({ space: 3 }) {
        Text(this.foodItem.name)
        Row() {
          Text() {
            Span('¥')
              .fontSize(10)
            Span(this.foodItem.price.toString())
              .fontColor($r('app.color.main_color'))
              .fontSize(14)
              .fontWeight(600)
          }

          MTAddCutView({ foodItem: this.foodItem })
        }
        .width('100%')
        .justifyContent(FlexAlign.SpaceBetween)
      }
      .layoutWeight(1)
      .alignItems(HorizontalAlign.Start)
    }
    .height(60)
    .alignItems(VerticalAlign.Top)
    .width('100%')
    .padding({ top: 12, left: 15, right: 15, bottom: 12 })
  }
}

1.5 清空购物车

CartStore.ets中增加清空方法:

static clearCart() {
  AppStorage.set('cartStore', [])
  getContext().eventHub.emit('changeCart')
}

购物车View中增加点击事件:

...
Text('清空购物车')
  .fontColor($r('app.color.search_font_color'))
  .fontSize(12)
  .onClick(() => {
    CartStore.clearCart()
  })
...

1.5 购物车数量和价格

在这里插入图片描述

修改MTBottomView,计算购物车数量和价格:

import { FoodItem } from '../models'

@Component
export struct MTBottomView {
  @Consume
  showCart: boolean
  @Consume cartList: FoodItem[]

  // 获取总数量
  getTotalCount() {
    return this.cartList.reduce((pre: number, item: FoodItem) => {
      return pre + item.count
    }, 0)
  }

  // 获取总价格
  getTotalPrice() {
    return this.cartList.reduce((pre: number, item: FoodItem) => {
      return pre + item.count * item.price
    }, 0)
  }

  build() {
    Row() {
      // 小哥+角标
      Badge({ value: this.getTotalCount().toString(), style: { badgeSize: 18 }, position: BadgePosition.Right }) {
        Image($r('app.media.ic_public_cart'))
          .height(69)
          .width(47)
          .position({
            y: -20
          })
      }
      .margin({ left: 28, right: 12 })
      .onClick(() => {
        this.showCart = !this.showCart
      })

      // 金额+描述
      Column() {
        Text() {
          Span('¥')
            .fontColor(Color.White)
            .fontSize(12)
          Span(this.getTotalPrice().toString())
            .fontColor(Color.White)
            .fontSize(25)
        }

        Text('预估另需配送费¥5')
          .fontColor($r('app.color.search_font_color'))
          .fontSize(12)
      }
      .alignItems(HorizontalAlign.Start)
      .layoutWeight(1)

      // 去结算
      Text('去结算')
        .width(80)
        .height(50)
        .fontSize(16)
        .backgroundColor($r('app.color.main_color'))
        .textAlign(TextAlign.Center)
        .borderRadius({
          topRight: 25,
          bottomRight: 25
        })
    }
    .height(50)
    .width('88%')
    .margin({ bottom: 20 })
    .backgroundColor(Color.Black)
    .borderRadius(26)
  }
}

二、小结

  • cartStore应用
  • 加减菜逻辑
  • 购物车逻辑
  • 事件总线

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/613516.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

IndexedDB解密:打开Web应用的数据存储之门

欢迎来到我的博客&#xff0c;代码的世界里&#xff0c;每一行都是一个故事 IndexedDB解密&#xff1a;打开Web应用的数据存储之门 前言IndexedDB简介数据库操作数据检索与索引异步操作与事件处理 前言 在Web的世界里&#xff0c;数据就像是一群旅行者&#xff0c;它们来自各个…

AGV混合型电机驱动器|伺服控制器CNS-MI50H系列对电机的要求

混合型电机驱动器 CNS-MI50H系列涵盖CNS-MI50HB-A、CNS-MI50HBN-A、CNS-MI50HDN-A、CNS-MI50HSN-A型号&#xff0c;专为 AGV 舵轮控制需求设计&#xff0c;集成舵轮转向角度控制和驱动电机闭环控制。支持增量式编码器&#xff0c;霍尔传感器&#xff0c; 角度电位计&#xff0c…

利用106短信群发平台能否提升沟通效率?

利用106短信群发平台确实能够显著提升沟通效率&#xff0c;具体体现在以下几个方面&#xff1a; 1.快速传递信息&#xff1a;106短信群发平台能够实现信息的快速传递。一旦设置好发送内容和接收群体&#xff0c;短信便能在瞬间发送至大量用户。这种即时性确保了信息的迅速传达…

Linux开发--Bootloader应用分析

Bootloader应用分析 一个嵌入式 Linux 系统从软件的角度看通常可以分为四个层次&#xff1a; 引导加载程序。包括固化在固件( firmware )中的 boot 代码(可选)&#xff0c;和 Boot Loader 两大部分。 Linux 内核。特定于嵌入式板子的定制内核以及内核的启动参数。 文件系统…

idea-自我快捷键-2

1. 书签 创建书签&#xff1a; 创建书签&#xff1a;F11创建特色标记书签&#xff1a;Ctrl F11快速添加助记符书签&#xff1a;ctrl shift 数字键 查看书签&#xff1a; shift F11快速定位到助记符书签&#xff1a;Ctrl 数字键 删除书签&#xff1a; delete 2. 自动…

2024年第四届电子信息工程与计算机科学国际会议(EIECS 2024)

2024年第四届电子信息工程与计算机科学国际会议(EIECS 2024) 2024 4th International Conference on Electronic Information Engineering and Computer Science 中国延吉 | 2024年9月27-29日 投稿截止日期&#xff1a;2023年7月15日 收录检索&#xff1a;EI Compendex和Sc…

Remix Client/Server 架构

Remix 框架是服务端渲染架构&#xff0c;当路由请求时生成 HTML 并返回浏览器。这种 SSR 是如何实现的呢&#xff1f;如果不使用 Remix 这种框架&#xff0c;可以在服务器段启动一个无头浏览器进行页面渲染并返回&#xff0c;代价就是要在服务器上启动一个 Chrome 服务&#xf…

微信小程序按钮去除边框线

通常我们去掉按钮边框直接设置 border:0 但是在小程序中无效&#xff0c;设置outline:none也没用&#xff0c;当然可能你会说加权重无效 实际上该样式是在伪元素::after内&#xff0c;主要你检查css 还看不到有这个关系&#xff0c;鹅厂就是坑多 类样式::after {border: non…

【北京迅为】《iTOP-3588从零搭建ubuntu环境手册》-第3章 Ubuntu20.04系统设置

RK3588是一款低功耗、高性能的处理器&#xff0c;适用于基于arm的PC和Edge计算设备、个人移动互联网设备等数字多媒体应用&#xff0c;RK3588支持8K视频编解码&#xff0c;内置GPU可以完全兼容OpenGLES 1.1、2.0和3.2。RK3588引入了新一代完全基于硬件的最大4800万像素ISP&…

论文精读-存内计算芯片研究进展及应用

文章目录 论文精读-存内计算芯片研究进展及应用概述背景介绍前人工作 存内计算3.1 SRAM存内计算3.2 DRAM存内计算3.3 ReRAM/PCM存内计算3.4 MRAM存内计算3.5 NOR Flash存内计算3.6 基于其他介质的存内计算3.7 存内计算芯片应用场景 总结QA 论文精读-存内计算芯片研究进展及应用…

Echarts旭日图的配置项,强大的层级关系展示图表。

ECharts中的旭日图&#xff08;Sunburst Chart&#xff09;是一种数据可视化图表&#xff0c;用于展示层级关系数据。它通常用于呈现树状结构或层级结构的数据&#xff0c;例如组织结构、文件目录结构、地理区域层级等。 旭日图通过圆形的方式展示数据的层级结构&#xff0c;每…

动手学深度学习16 Pytorch神经网络基础

动手学深度学习16 Pytorch神经网络基础 1. 模型构造2. 参数管理1. state_dict()2. normal_() zeros_()3. xavier初始化共享参数的好处 3. 自定义层4. 读写文件net.eval() 评估模式 QA 1. 模型构造 定义隐藏层–模型结构定义前向函数–模型结构的调用 import torch from torch…

Windows密码破解常见手段

mimikatz导出lsass破解 如果域管在成员机器上登录过&#xff0c;那么密码机会保存到lsass.exe进程当中&#xff0c;可以通过mimikatz读取密码 用本地管理员登录本地机器 导出hash reg add HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest /v UseLogonCred…

大模型,阿里云不做选择题 | 最新快讯

什么加速了云的发展&#xff1f; 自 2006 年云计算诞生之日算起&#xff0c;互联网和移动应用、云原生技术普及、企业向先进技术架构演进、中企全球化等因素&#xff0c;先后塑造了云计算的内在与外表&#xff0c;造就了一个数万亿规模的行业。 毋庸置疑的是&#xff0c;生成式…

wordpress 访问文章内容页 notfound

解决&#xff1a; 程序对应的伪静态规则文件.htaccess是空的 网站根目录下要有 .htaccess 文件&#xff0c;然后将下面的代码复制进去。 <ifmodule mod_rewrite.c>RewriteEngine OnRewriteBase /RewriteRule ^index\.php$ - [L]RewriteCond %{REQUEST_FILENAME} !-fRew…

python + word文本框中文字识别并替换【真替换,不只是识别】

1. 简单描述 在一些转换场景下&#xff0c;文本框不会被转换&#xff0c;需要先识别成文字内容。 【识别的文字段落可能会和实际看到的效果有些差异&#xff0c;后续还需校对&#xff0c;如下图】。 不足&#xff1a;除了上面说的那个情况&#xff08;上图说的问题&#xff0…

同时安装多个nodejs版本可切换使用,或者用nvm管理、切换nodejs版本(两个详细方法)

目录 一.使用nvm的方法&#xff1a; 1.卸载nodejs 2.前往官网下载nvm 3.安装nvm 4.查看安装是否完成 5.配置路径和淘宝镜像 6.查看和安装各个版本的nodejs 7.nvm的常用命令 二.不使用nvm&#xff0c;安装多个版本&#xff1a; 1.安装不同版本的nodejs 2.解压到你想放…

天猫最热销的三款随身WiFi,哪一款直播最好用?2024公认最好的随身WiFi,天猫上的随身wifi是正规产品吗

近期有小伙伴问我&#xff1a;“小编、小编我要当户外博主了&#xff0c;想买一个随身WiFi&#xff0c;但是天猫榜单前三的随身WiFi自己都没有听说过&#xff0c;到底入手哪个比较好&#xff1f;”三款随身WiFi呢&#xff0c;分别是格行随身WiFi、迅优随身WiFi、小米随身WiFi&a…

STL-Setmap

前言 大家好&#xff0c;我是jiantaoyab&#xff0c;我们将进入到CSTL 的学习。STL在各各C的头文件中&#xff0c;以源代码的形式出现&#xff0c;不仅要会用&#xff0c;还要了解底层的实现。源码之前&#xff0c;了无秘密。 STL六大组件 Container通过Allocator取得数据储存…

系统集成项目管理工程师第4章思维导图发布

2024年开年&#xff0c;软考系统集成项目管理工程师官方教程&#xff0c;迎来了阔别7年的大改版&#xff0c;改版之后的软考中项考试&#xff0c;离同宗兄弟高项考试渐行渐远。 中项第3版教程&#xff0c;仅仅从教程来看&#xff0c;其难度已经不亚于高级的信息系统项目管理师&…