1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| import { defineStore } from 'pinia' import { ref, computed } from 'vue'
export const useCartStore = defineStore('cart', () => { const items = ref([])
const totalPrice = computed(() => { return items.value.reduce((sum, item) => { return sum + item.price * item.quantity }, 0) })
const totalCount = computed(() => { return items.value.reduce((sum, item) => sum + item.quantity, 0) })
function addItem(product, quantity = 1) { const existingItem = items.value.find(item => item.id === product.id)
if (existingItem) { existingItem.quantity += quantity } else { items.value.push({ id: product.id, name: product.name, price: product.price, quantity }) } }
function removeItem(productId) { const index = items.value.findIndex(item => item.id === productId) if (index > -1) { items.value.splice(index, 1) } }
function updateQuantity(productId, quantity) { const item = items.value.find(item => item.id === productId) if (item) { item.quantity = Math.max(0, quantity) if (item.quantity === 0) { removeItem(productId) } } }
function clearCart() { items.value = [] }
return { items, totalPrice, totalCount, addItem, removeItem, updateQuantity, clearCart } })
|