102 lines
2.5 KiB
TypeScript
102 lines
2.5 KiB
TypeScript
import { defineStore } from 'pinia'
|
||
import { shop, product } from '../api/shop'
|
||
import { useProducts } from './products'
|
||
|
||
/**
|
||
* 购物车商品列表数据定义
|
||
*/
|
||
type CartItem = {
|
||
id: number,
|
||
quantity: number,
|
||
}
|
||
|
||
/**
|
||
* 购物车商品列表信息定义
|
||
*/
|
||
type CartItemInfo = {
|
||
// 商品ID
|
||
id: number,
|
||
// 标题
|
||
title: string,
|
||
// 价格
|
||
price: number,
|
||
// 数量
|
||
quantity: number,
|
||
}
|
||
|
||
/**
|
||
* state定义
|
||
*/
|
||
type state = {
|
||
// 购物车商品列表数据
|
||
items: CartItem[],
|
||
// 标记购买状态
|
||
checkoutStatus: null | string
|
||
}
|
||
|
||
export const useCart = defineStore('cart', {
|
||
state: (): state => {
|
||
return {
|
||
items: [],
|
||
checkoutStatus: null
|
||
}
|
||
},
|
||
|
||
getters: {
|
||
cartProducts (): CartItemInfo[] {
|
||
return this.items.map(({ id, quantity }) => {
|
||
const product = useProducts().all.find(product => product.id === id) as product
|
||
|
||
return {
|
||
id: product.id,
|
||
title: product.title,
|
||
price: product.price,
|
||
quantity
|
||
}
|
||
})
|
||
},
|
||
|
||
cartTotalPrice () {
|
||
const products = this.cartProducts as CartItemInfo[] // 不知道为啥直接this.cartProducts.reduce就会报错,必须要转换一下
|
||
return products.reduce((total, product) => {
|
||
return total + product.price * product.quantity
|
||
}, 0)
|
||
}
|
||
},
|
||
|
||
actions: {
|
||
checkout () {
|
||
const savedCartItems = [...this.items]
|
||
this.checkoutStatus = null
|
||
// empty cart
|
||
this.items = []
|
||
shop.buyProducts(
|
||
() => this.checkoutStatus = 'successful',
|
||
() => {
|
||
this.checkoutStatus = 'failed'
|
||
this.items = savedCartItems
|
||
}
|
||
)
|
||
},
|
||
|
||
addProductToCart (product: product, number: number) {
|
||
this.checkoutStatus = null
|
||
|
||
if (product.inventory > 0) {
|
||
const cartItem = this.items.find(item => item.id === product.id)
|
||
|
||
if (!cartItem) {
|
||
this.items.push({
|
||
id: product.id,
|
||
quantity: number
|
||
})
|
||
} else {
|
||
cartItem.quantity += number
|
||
}
|
||
|
||
// remove 1 item from stock
|
||
useProducts().decrementProductInventory(product.id, number)
|
||
}
|
||
}
|
||
}
|
||
}) |