You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

35 lines
903 B

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))
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, addItem, removeItem, updateQty, clearCart }
})