forked from sohilpro/pet-shop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcart.js
62 lines (60 loc) · 1.29 KB
/
cart.js
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { defineStore } from "pinia";
import { useToast } from "vue-toastification";
const toast = useToast();
export const useCart = defineStore("cart", {
state: () => {
return {
cart: [],
};
},
getters: {
count(state) {
return state.cart.length;
},
allItems(state) {
return state.cart;
},
totalAmount(state) {
return state.cart.reduce((acc, product) => {
return acc + product.price * product.qty;
}, 0);
},
},
actions: {
addToCart(product) {
const item = this.cart.find((p) => p.id == product.id);
if (!item) {
this.cart.push({
...product,
qty: 1,
});
} else {
item.qty++;
}
toast.success("محصولت با موفقیت به سبدت اضاف شد 🤩");
},
remove(id) {
this.cart = this.cart.filter((p) => p.id != id);
},
increment(id) {
const item = this.cart.find((p) => p.id == id);
if (item) {
item.qty++;
}
},
decrement(id) {
const item = this.cart.find((p) => p.id == id);
if (item) {
if (item.quantity > 1) {
item.qty--;
}
}
},
clearCart() {
this.cart = [];
},
},
persist: {
storage: persistedState.localStorage,
},
});