Skip to content

Commit de28a24

Browse files
committed
Save state to localStorage
1 parent 9552ea1 commit de28a24

File tree

2 files changed

+40
-3
lines changed

2 files changed

+40
-3
lines changed

src/services/storage.js

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import {merge} from 'lodash'
2+
3+
export default class Storage {
4+
5+
constructor(key) {
6+
7+
this.key = key;
8+
9+
if (!window.localStorage) {
10+
console.error('localStorage not available');
11+
}
12+
}
13+
14+
plugin = store => {
15+
16+
store.replaceState(merge(
17+
store.state,
18+
this.load()
19+
));
20+
21+
this.save(store.state);
22+
23+
store.subscribe((mutation, state) => {
24+
this.save(state);
25+
})
26+
};
27+
28+
load() {
29+
return JSON.parse(window.localStorage.getItem(this.key) || '{}');
30+
}
31+
32+
save(data) {
33+
window.localStorage.setItem(this.key, JSON.stringify(data));
34+
}
35+
}

src/store.js

+5-3
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,17 @@
11
import Vue from 'vue';
22
import Vuex from 'vuex';
33

4-
import Ticket from "@/models/ticket";
4+
import Storage from "@/services/storage";
55

66
Vue.use(Vuex);
77

88
export default new Vuex.Store({
99
state: {
10-
tickets: [
11-
],
10+
tickets: [],
1211
},
12+
plugins: [
13+
new Storage('ticket-calc').plugin
14+
],
1315
getters: {
1416
tickets: state => state.tickets,
1517
},

0 commit comments

Comments
 (0)