feature: 购物车完整demo

This commit is contained in:
2022-04-28 11:57:53 +08:00
parent ca37a1831f
commit 6dece8bccc
7 changed files with 155 additions and 16 deletions

57
src/store/cart.ts Normal file
View File

@@ -0,0 +1,57 @@
import { defineStore } from "pinia";
import { buyProducts, IProduct } from "@/api/shop";
import { useProductStore } from "@/store/product";
type CartProduct = {
quantity: number
} & IProduct
enum checkoutStatus {
PENDING = "未结算",
SUCCESS = "结算成功",
FALSE = "结算失败"
}
export const useCartStore = defineStore('cart', {
state: () => ( {
cartProducts: [] as CartProduct[],
checkStatus: checkoutStatus.PENDING
} ),
getters: {
totalPrice( state ) {
return state.cartProducts.reduce(( pre, cur ) => {
return pre + cur.price * cur.quantity
}, 0)
}
},
actions: {
addProductToCart( product: IProduct ) {
if ( product.inventory < 1 ) {
return
}
const cartItem: CartProduct | undefined = this.cartProducts.find(item => item.id === product.id)
if ( cartItem ) {
cartItem.quantity++
} else {
this.cartProducts.push({
id: product.id,
name: product.name,
inventory: product.inventory,
price: product.price,
quantity: 1
})
}
const productStore = useProductStore()
productStore.decrementProductInventory(product)
},
async checkout() {
const result = await buyProducts()
if ( result ) {
this.checkStatus = checkoutStatus.SUCCESS
this.cartProducts = []
} else {
this.checkStatus = checkoutStatus.FALSE
}
}
}
})

20
src/store/product.ts Normal file
View File

@@ -0,0 +1,20 @@
import { defineStore } from "pinia";
import { getProducts, IProduct } from "@/api/shop";
export const useProductStore = defineStore('product', {
state: () => ( {
all: [] as IProduct[]
} ),
getters: {},
actions: {
async loadAllProducts() {
this.all = await getProducts()
},
decrementProductInventory( product: IProduct ) {
const productItem = this.all.find(item => item.id === product.id)
if ( productItem ) {
productItem.inventory--
}
}
}
})