Initial commit: 商品售卖网站

This commit is contained in:
2026-04-13 07:20:09 +08:00
commit c6154273f2
865 changed files with 26573 additions and 0 deletions
+62
View File
@@ -0,0 +1,62 @@
import { ref, watch } from 'vue'
import { defineStore } from 'pinia'
import { cartApi } from '../api'
export const useCartStore = defineStore('cart', () => {
const items = ref<any[]>([])
const loading = ref(false)
const totalAmount = ref(0)
const totalCount = ref(0)
async function fetchCart() {
loading.value = true
try {
const res: any = await cartApi.list()
items.value = res.data || []
calcTotals()
} finally {
loading.value = false
}
}
async function addItem(productId: number, quantity: number) {
await cartApi.add({ product_id: productId, quantity })
await fetchCart()
}
async function updateItem(id: number, quantity: number) {
await cartApi.update(id, { quantity })
await fetchCart()
}
async function removeItem(id: number) {
await cartApi.delete(id)
await fetchCart()
}
async function removeItems(ids: number[]) {
for (const id of ids) {
await cartApi.delete(id)
}
await fetchCart()
}
function calcTotals() {
totalAmount.value = items.value.reduce((sum, item) => sum + (item.product?.price || 0) * item.quantity, 0)
totalCount.value = items.value.reduce((sum, item) => sum + item.quantity, 0)
}
watch(items, calcTotals, { deep: true })
return {
items,
loading,
totalAmount,
totalCount,
fetchCart,
addItem,
updateItem,
removeItem,
removeItems
}
})