美文网首页
美团外卖-加入购物车

美团外卖-加入购物车

作者: 家乡的蝈蝈 | 来源:发表于2024-02-18 13:36 被阅读0次

1.1、提供加减购物车的方法

  我们需要持久化的数据,使用 PersistentStorage.PersistProp(CART_KEY, '[]')

// 持久化的数据, []表示初始化为数组
PersistentStorage.PersistProp<string>("user_cart", "[]")

// 提供加减购物车的方法
// 既可以加菜又可以减菜
const addCutCart = (type:'add' | 'cut', item:FoodItem) => {
  const list = getCarts()
  const f = list.find(f => f.id === item.id)
  if (type === 'add') { // 加菜
    if (f) {
      // 找到了
      f.count++
    } else {
      item.count = 1
      list.unshift(item) // unshift在数组头部追加,push在数组尾部追加
    }
  } else { // 减菜
    if (f && f.count > 0) {
      f.count--
      if (f.count === 0) {
        const index = list.findIndex(ff => ff.id === item.id)
        // 移除菜品数据
        list.splice(index, 1)
      }
    }
  }
  // 不管list有没有发生了任何变化
  AppStorage.Set<string>("user_cart", JSON.stringify(list))
}

1.2、获取购物车里面的所有数据

// 获取购物车里面的所有数据
const getCarts = () => {
  // []表示短路表达式
  return JSON.parse(AppStorage.Get<string>("user_cart") || '[]') as FoodItem[]
}

1.3、采用Provide和Consume进行跨层组件传递

  购物车通过StorageLink进行数据绑定- 采用Provide和Consume来实现

1.3.1、在顶层组件MeiTuan中使用Provide

struct MeiTuan {
  @StorageLink("user_cart")
  @Watch("updateCartJSON") // watch必须写在其他修饰符下面
  cartJSON:string = ""
  @Provide
  cartList:FoodItem[] = []
  updateCartJSON() {
    // 此时更新我们的购物车数据
    this.cartList = getCarts() // 反序列化将字符串转成对象
  }
}

1.3.2、在购物车MTCart中使用Consume

// 购物车组件
@Component
struct MTCart {
  @Consume
  cartList:FoodItem[]
  build() {
    Column() {
      // 顶部标题
      Row() {
        Text('购物车')
          .fontSize(12)
        Text('清空购物车')
          .fontSize(12)
          .fontColor('#999')
      }
      .justifyContent(FlexAlign.SpaceBetween)
      .width('100%')
      .height(40)
      .padding({
        left:15,
        right:15
      })
      .border({
        color:'#f5f5f5',
        width: {
          bottom:0.5
        }
      })
      // 封装N个购物车的内容
      List({space:30}) {
        ForEach(this.cartList, (item:FoodItem) => {
          ListItem() {
            MTCardItem({item:item}) // 自定义组件的参数默认为一个对象
          }
        })
      }
    }
    .height('50%')
    .width('100%')
    .backgroundColor(Color.White)
  }
}

相关文章

网友评论

      本文标题:美团外卖-加入购物车

      本文链接:https://www.haomeiwen.com/subject/dwuqadtx.html