feat: Add cart store for catalog quantity sync

- Create Pinia cart store to manage cart state globally
- Sync quantity changes between catalog cards and cart sidebar
- Improve product card design with borders and hover effects
- Fix cart sync when updating quantity via minus button or input field
This commit is contained in:
2026-03-14 16:59:45 -05:00
parent 1d37ce42dc
commit 78923ddb6e
3 changed files with 93 additions and 57 deletions

View File

@@ -35,21 +35,32 @@ export default {
Card,
Cart
},
setup() {
const cartStore = useCartStore();
return { cartStore };
},
data() {
return {
api: inject('api'),
cartItems: [],
items: [],
};
},
computed: {
cartItems: {
get() {
return this.cartStore.items;
},
set(value) {
this.cartStore.items = value;
}
},
cartCount() {
return this.cartStore.cartCount;
}
},
created() {
this.fetchProducts();
},
computed: {
cartCount() {
return this.cartItems.reduce((sum, item) => sum + item.quantity, 0);
}
},
methods: {
fetchProducts() {
this.api.getProducts()
@@ -85,35 +96,17 @@ export default {
},
addToCart(item) {
if (item.quantity <= 0) return;
const existingItem = this.cartItems.find(i => i.id === item.id);
if (existingItem) {
existingItem.quantity = item.quantity;
} else {
this.cartItems.push({
id: item.id,
name: item.name,
img: item.img,
price: item.price,
quantity: item.quantity
});
}
this.cartStore.addItem(item);
},
removeFromCart(itemId) {
const index = this.cartItems.findIndex(i => i.id === itemId);
if (index > -1) {
this.cartItems.splice(index, 1);
}
this.cartStore.removeItem(itemId);
const item = this.items.find(i => i.id === itemId);
if (item) {
item.quantity = 0;
}
},
updateCartQuantity({ itemId, quantity }) {
const cartItem = this.cartItems.find(i => i.id === itemId);
if (cartItem) {
cartItem.quantity = quantity;
}
this.cartStore.updateQuantity({ itemId, quantity });
const productItem = this.items.find(i => i.id === itemId);
if (productItem) {
productItem.quantity = quantity;

43
src/stores/cart.js Normal file
View File

@@ -0,0 +1,43 @@
import { defineStore } from 'pinia'
export const useCartStore = defineStore('cart', {
state: () => ({
items: []
}),
getters: {
cartCount: (state) => state.items.reduce((sum, item) => sum + item.quantity, 0),
cartTotal: (state) => state.items.reduce((sum, item) => sum + (item.price * item.quantity), 0)
},
actions: {
addItem(product) {
const existing = this.items.find(i => i.id === product.id)
if (existing) {
existing.quantity = product.quantity
} else {
this.items.push({
id: product.id,
name: product.name,
img: product.img,
price: product.price,
quantity: product.quantity,
measuring_unit: product.measuring_unit || 'Unidad'
})
}
},
removeItem(itemId) {
const index = this.items.findIndex(i => i.id === itemId)
if (index > -1) {
this.items.splice(index, 1)
}
},
updateQuantity({ itemId, quantity }) {
const item = this.items.find(i => i.id === itemId)
if (item) {
item.quantity = quantity
}
},
clearCart() {
this.items = []
}
}
})