微信原生小程序ts+mobx-miniprogram实现购物车

601 阅读1分钟

书接上文,mobx-miniprogram在实现购物车的时候遇到了不少坑,比如修改了参数,结果界面不更新等等问题,所以在这里做个汇总

废话不多说,先看代码:

目录:

image.png

import { observable, action } from 'mobx-miniprogram'
import { BehaviorWithStore } from 'mobx-miniprogram-bindings'
export type Product = {
  id: number
  name: string
  price: number
  stock?: number
  [key: string]: any
}
export type CartItem = {
  productId: number
  quantity: number
  name: string
  price: number
}
export const cartStore = observable({
  cartItems: [] as CartItem[],

  get totalProducts() {
    return this.cartItems.reduce((acc: any, item: any) => {
      return acc + item.quantity
    }, 0)
  },

  addToCart: action(function (product: Product) {
    const item = cartStore.cartItems.find(item => item.productId === product.id)
    if (item) {
      cartStore.updateQuantity(item, item.quantity + 1)
    } else {
      cartStore.cartItems = [...cartStore.cartItems, {
        productId: product.id,
        quantity: 1,
        name: product.name,
        price: product.price
      }]
    }
  }),
  updateQuantity: action(function (item: CartItem, quantity: number) {
    cartStore.cartItems = cartStore.cartItems.map((cart) => {
      if (cart.productId === item.productId) {
        cart.quantity = quantity
      }
      return cart
    })
  })
})

export const cartBehavior = BehaviorWithStore({
  storeBindings: {
    store: cartStore,
    fields: ['totalProducts', 'cartItems'],
    actions: [],
  }
});

目录:

image.png

import {cartStore,cartBehavior} from '../../store/cart'
Component({
  behaviors:[cartBehavior],
  data:{
    products:[
      {
        id:1,
        name:'product 1',
        price:10
      },
      {
        id:2,
        name:'product 2',
        price:20
      },
      {
        id:3,
        name:'product 3',
        price:30
      }
    ]
  },
  methods:{
    addToCart:function(e:WechatMiniprogram.CustomEvent){
      cartStore.addToCart(e.currentTarget.dataset.product)
    },
    onChange:function (e:WechatMiniprogram.CustomEvent) {
      cartStore.updateQuantity(e.currentTarget.dataset.cart,e.detail as any)
    }
  }
})
<!--pages/products/products.wxml-->
<view wx:for="{{products}}" wx:key="id">
  <text>{{item.name}} ¥ {{item.price}}</text>
  <button bindtap="addToCart" data-product="{{item}}">Add to cart</button>
</view>

<view>
  <text>{{totalProducts}}</text>
</view>

<view>
  <text>购物车</text>
</view>

<view wx:for="{{cartItems}}" wx:key="id">
  <text>{{item.name}} ¥ {{item.price}}</text>
  <van-stepper data-cart="{{item}}" value="{{ item.quantity }}" min="1" integer bind:change="onChange" />
</view>

这里面需要注意的就是mobx不能直接修改数据,这样页面是不更新的,只能通过替换源数据