超市购物车

This commit is contained in:
weiwei committed 2025-06-19 15:15:28 +08:00
1 parent d3c67fed9b
commit f2dd10aefb
6 files changed
+236 -32

No files matched your search

+91
View File
@@ -0,0 +1,91 @@
import { defineStore } from "pinia"
import { foodApi } from "../api"
export const useCartStore = defineStore("cartStore", {
state: () => ({
cart: JSON.parse(uni.getStorageSync("cart") || "[]"),
}),
getters: {
totCount(state) {
return state.cart.reduce((prev, cur) => {
return prev + cur.productCount
}, 0)
},
totPrice(state) {
return state.cart
.map((item) => Number(item.totalPrice))
.reduce((prev, cur) => prev + cur, 0)
.toFixed(2)
},
},
actions: {
// 更新购物车中商品数量的方法
updataGoodsCount(goods) {
// 从购物车数组对象中查找到需要更新的这件商品
const findResult = this.cart.find((item) => {
return item.goods_id === goods.goods_id
})
// 如果查找到,就把这件商品传递的最新数量保存,并本地存储
if (findResult) {
findResult.goods_count = goods.goods_count
this.saveToStorage()
}
},
// ===================================================================
saveToStorage() {
uni.setStorageSync("cart", JSON.stringify(this.cart))
},
saveShoppingCart(cartList: any) {
this.cart = cartList
this.saveToStorage()
},
addGoodsItemToCart(goodsItem: any) {
const findResult = this.cart.find((item: any) => {
return item.productId === goodsItem.productId
})
if (!findResult) {
this.cart.unshift(goodsItem)
} else {
findResult.productCount++
}
this.saveToStorage()
},
async addProductCount(productId: string) {
this.cart.forEach((item: any) => {
if (item.productId === productId) {
item.productCount++
}
})
await this.updateShopCart()
await this.getShopCart()
},
async removeProductCount(productId: string) {
this.cart.forEach((item: any) => {
if (item.productId === productId) {
item.productCount--
}
})
await this.updateShopCart()
await this.getShopCart()
},
async getShopCart() {
const { data } = await foodApi.getShopCar({ merchantId: "1931916121241079810", hardType: "SUPERMARKET" })
this.saveShoppingCart(data ?? [])
},
async updateShopCart() {
const list = this.cart
.filter((v) => v.productCount && v.productCount > 0)
.map((v) => {
return {
productCount: v.productCount,
productId: v.productId,
}
})
const { code }: any = await foodApi.updateShopCar({ merchantId: "1931916121241079810", list, hardType: "SUPERMARKET" })
if (code == 0) return await this.getShopCart()
uni.showToast({ title: "更新购物车失败", icon: "none" })
},
},
})