-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
107 lines (100 loc) · 2.38 KB
/
index.js
File metadata and controls
107 lines (100 loc) · 2.38 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import Vue from "vue";
import { omit } from "lodash";
import {
ADD_ITEM_TO_CART,
REMOVE_ITEM_FROM_CART,
DELETE_VARIATION,
LOAD_CART_FROM_STORAGE,
CLEAR_CART,
CART_ITEMS,
CART_TOTAL,
NUM_ITEMS,
} from "./constants.type";
function setCartStorage(items) {
window.localStorage.setItem("cart", JSON.stringify(items));
}
const state = {
items: {},
};
const actions = {
[ADD_ITEM_TO_CART]({ commit }, { item, sku }) {
commit(ADD_ITEM_TO_CART, { item, sku });
},
[REMOVE_ITEM_FROM_CART]({ commit }, item) {
commit(REMOVE_ITEM_FROM_CART, item);
},
[DELETE_VARIATION]({ commit }, item) {
commit(DELETE_VARIATION, item);
},
[LOAD_CART_FROM_STORAGE]({ commit }) {
commit(LOAD_CART_FROM_STORAGE);
},
[CLEAR_CART]({ commit }) {
commit(CLEAR_CART);
},
};
const mutations = {
[ADD_ITEM_TO_CART](state, { item, sku }) {
if (state.items[sku] || !item) {
Vue.set(state.items[sku], "quantity", state.items[sku].quantity + 1);
} else {
Vue.set(state.items, sku, {
...omit(item, ["variants"]),
variant: item.variants[sku].name,
price: item.variants[sku].price,
quantity: 1,
});
}
setCartStorage(state.items);
},
[REMOVE_ITEM_FROM_CART](state, sku) {
if (state.items[sku]) {
let finalQuantity = state.items[sku].quantity - 1;
if (finalQuantity <= 0) {
Vue.delete(state.items, sku);
} else {
Vue.set(state.items[sku], "quantity", finalQuantity);
}
}
setCartStorage(state.items);
},
[DELETE_VARIATION](state, sku) {
if (state.items[sku]) {
Vue.delete(state.items, sku);
}
setCartStorage(state.items);
},
[LOAD_CART_FROM_STORAGE](state) {
let storedItems = JSON.parse(window.localStorage.getItem("cart"));
state.items = storedItems || {};
},
[CLEAR_CART](state) {
Vue.set(state, "items", {});
setCartStorage(state.items);
},
};
const getters = {
[CART_TOTAL](state) {
let total = 0;
Object.keys(state.items).forEach((item) => {
total += state.items[item].price * state.items[item].quantity;
});
return total;
},
[NUM_ITEMS](state) {
let total = 0;
Object.keys(state.items).forEach((item) => {
total += state.items[item].quantity;
});
return total;
},
[CART_ITEMS](state) {
return state.items;
},
};
export default {
state,
actions,
mutations,
getters,
};