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
|
// stores/cart.js
import { defineStore } from "pinia";
export const useCartStore = defineStore("cart", {
state: () => ({
items: [],
}),
getters: {
totalPrice: (state) => {
return state.items.reduce((total, item) => {
return total + item.price * item.quantity;
}, 0);
},
itemCount: (state) => {
return state.items.reduce((count, item) => {
return count + item.quantity;
}, 0);
},
},
actions: {
addItem(product) {
const existingItem = this.items.find((item) => item.id === product.id);
if (existingItem) {
existingItem.quantity++;
} else {
this.items.push({
...product,
quantity: 1,
});
}
},
removeItem(productId) {
const index = this.items.findIndex((item) => item.id === productId);
if (index > -1) {
this.items.splice(index, 1);
}
},
updateQuantity(productId, quantity) {
const item = this.items.find((item) => item.id === productId);
if (item) {
item.quantity = quantity;
}
},
clearCart() {
this.items = [];
},
},
});
|