import { defineStore } from 'pinia'
|
|
import { ref, computed } from 'vue'
|
|
|
|
export const useCartStore = defineStore('cart', () => {
|
|
const items = ref([])
|
|
|
|
const totalCount = computed(() => items.value.reduce((s, i) => s + i.qty, 0))
|
|
const totalAmount = computed(() => items.value.reduce((s, i) => s + i.product.price * i.qty, 0))
|
|
|
|
function addItem(product, qty = 1) {
|
|
const exist = items.value.find(i => i.product.id === product.id)
|
|
if (exist) {
|
|
exist.qty += qty
|
|
} else {
|
|
items.value.push({ product: { ...product }, qty })
|
|
}
|
|
}
|
|
|
|
function removeItem(productId) {
|
|
items.value = items.value.filter(i => i.product.id !== productId)
|
|
}
|
|
|
|
function updateQty(productId, qty) {
|
|
const item = items.value.find(i => i.product.id === productId)
|
|
if (item) {
|
|
if (qty <= 0) removeItem(productId)
|
|
else item.qty = qty
|
|
}
|
|
}
|
|
|
|
function clearCart() {
|
|
items.value = []
|
|
}
|
|
|
|
return { items, totalCount, totalAmount, addItem, removeItem, updateQty, clearCart }
|
|
})
|