templates2.Store.Nuxt/app/composables/useCart.ts
w4c-templates 228f2f01f2
Some checks failed
CI / quality (push) Has been cancelled
chore(template): publish Store.Nuxt
2026-10-11 23:24:30 +03:00

36 lines
1.4 KiB
TypeScript

import type { CartItem } from '#shared/types';
/** Cart state shared across the app; persisted to localStorage by plugins/cart.client.ts. */
export function useCart() {
const items = useState<CartItem[]>('cart-items', () => []);
const count = computed(() => items.value.reduce((n, i) => n + i.quantity, 0));
const total = computed(() => items.value.reduce((n, i) => n + i.price * i.quantity, 0));
function add(item: Omit<CartItem, 'quantity'>, quantity = 1) {
const idx = items.value.findIndex((i) => i.productId === item.productId && i.variant === item.variant);
if (idx >= 0) {
items.value = items.value.map((i, k) => (k === idx ? { ...i, quantity: Math.min(99, i.quantity + quantity) } : i));
} else {
items.value = [...items.value, { ...item, quantity }];
}
}
function setQuantity(productId: string, variant: string | undefined, quantity: number) {
items.value =
quantity <= 0
? items.value.filter((i) => !(i.productId === productId && i.variant === variant))
: items.value.map((i) => (i.productId === productId && i.variant === variant ? { ...i, quantity: Math.min(99, quantity) } : i));
}
function remove(productId: string, variant: string | undefined) {
items.value = items.value.filter((i) => !(i.productId === productId && i.variant === variant));
}
function clear() {
items.value = [];
}
return { items, count, total, add, setQuantity, remove, clear };
}