|
| 1 | +import Vue from 'vue'; |
| 2 | +import Vuex from 'vuex'; |
| 3 | +import VuexPersistence from 'vuex-persist'; |
| 4 | + |
| 5 | +Vue.use(Vuex); |
| 6 | + |
| 7 | +const localStorageKey = 'vuex'; |
| 8 | + |
| 9 | +const vuexPersistence = new VuexPersistence({ |
| 10 | + key: localStorageKey, |
| 11 | + storage: window.localStorage, |
| 12 | + reducer: state => ({ cart: state.cart }), |
| 13 | +}); |
| 14 | + |
| 15 | +/* eslint-disable no-param-reassign */ |
| 16 | +export default new Vuex.Store({ |
| 17 | + state: { |
| 18 | + cart: {}, |
| 19 | + listener: null, |
| 20 | + }, |
| 21 | + getters: { |
| 22 | + cartCount(state) { |
| 23 | + return Object.values(state.cart).reduce((acc, cur) => acc + cur.count, 0); |
| 24 | + }, |
| 25 | + cartTotal(state) { |
| 26 | + return Object.values(state.cart) |
| 27 | + .reduce((acc, cur) => acc + cur.price * cur.count, 0) |
| 28 | + .toFixed(2); |
| 29 | + }, |
| 30 | + }, |
| 31 | + mutations: { |
| 32 | + addToCart(state, item) { |
| 33 | + if (!state.cart[item.name]) { |
| 34 | + state.cart[item.name] = { ...item, count: 0 }; |
| 35 | + } |
| 36 | + state.cart[item.name].count += 1; |
| 37 | + }, |
| 38 | + setListener(state, listener) { |
| 39 | + state.listener = listener; |
| 40 | + }, |
| 41 | + setCart(state, cart) { |
| 42 | + state.cart = cart; |
| 43 | + }, |
| 44 | + setItemCount(state, { name, count }) { |
| 45 | + if (count === 0) { |
| 46 | + Vue.delete(state.cart, name); |
| 47 | + return; |
| 48 | + } |
| 49 | + state.cart[name].count = count; |
| 50 | + }, |
| 51 | + removeCartItem(state, name) { |
| 52 | + Vue.delete(state.cart, name); |
| 53 | + }, |
| 54 | + }, |
| 55 | + actions: { |
| 56 | + listenToStorage({ commit, state }) { |
| 57 | + console.log('listening'); |
| 58 | + |
| 59 | + const listener = (e) => { |
| 60 | + if (e.key !== localStorageKey) { |
| 61 | + return; |
| 62 | + } |
| 63 | + const current = JSON.stringify({ cart: state.cart }); |
| 64 | + if (current === e.newValue) { |
| 65 | + return; |
| 66 | + } |
| 67 | + console.log('updating cart from other tab'); |
| 68 | + |
| 69 | + commit('setCart', JSON.parse(e.newValue).cart); |
| 70 | + }; |
| 71 | + window.addEventListener('storage', listener); |
| 72 | + commit('setListener', listener); |
| 73 | + }, |
| 74 | + unlisten({ commit, state }) { |
| 75 | + if (state.listener) { |
| 76 | + window.removeEventListener('storage', state.listener); |
| 77 | + commit('setListener', null); |
| 78 | + } |
| 79 | + }, |
| 80 | + }, |
| 81 | + plugins: [vuexPersistence.plugin], |
| 82 | +}); |
0 commit comments