feature: 购物车完整demo
This commit is contained in:
57
src/store/cart.ts
Normal file
57
src/store/cart.ts
Normal 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
20
src/store/product.ts
Normal 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--
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user