1 | import { MemoryStorage, WebStorage } from './storage';
|
2 |
|
3 |
|
4 | const _global = (typeof window !== 'undefined' ? window : global || {});
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | const VueStorage = {
|
10 | |
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | install(Vue, options = {}) {
|
18 | const _options = {
|
19 | ...options,
|
20 | storage: options.storage || 'local',
|
21 | name: options.name || 'ls',
|
22 | };
|
23 |
|
24 | if (_options.storage && ['memory', 'local', 'session'].indexOf(_options.storage) === -1) {
|
25 | throw new Error(`Vue-ls: Storage "${_options.storage}" is not supported`);
|
26 | }
|
27 |
|
28 | let store = null;
|
29 |
|
30 | switch(_options.storage) {
|
31 | case 'local':
|
32 | store = 'localStorage' in _global
|
33 | ? _global.localStorage
|
34 | : null
|
35 | ;
|
36 | break;
|
37 |
|
38 | case 'session':
|
39 | store = 'sessionStorage' in _global
|
40 | ? _global.sessionStorage
|
41 | : null
|
42 | ;
|
43 | break;
|
44 | case 'memory':
|
45 | store = MemoryStorage;
|
46 | break;
|
47 | }
|
48 |
|
49 | if (!store) {
|
50 | store = MemoryStorage;
|
51 |
|
52 | console.error(`Vue-ls: Storage "${_options.storage}" is not supported your system, use memory storage`);
|
53 | }
|
54 |
|
55 | const ls = new WebStorage(store);
|
56 |
|
57 | ls.setOptions(Object.assign(ls.options, {
|
58 | namespace: '',
|
59 | }, _options || {}));
|
60 |
|
61 | Vue[_options.name] = ls;
|
62 | Object.defineProperty(Vue.prototype || Vue.config.globalProperties, `$${_options.name}`, {
|
63 | |
64 |
|
65 |
|
66 |
|
67 |
|
68 | get() {
|
69 | return ls;
|
70 | },
|
71 | });
|
72 | },
|
73 | };
|
74 |
|
75 |
|
76 | _global.VueStorage = VueStorage;
|
77 |
|
78 | export default VueStorage;
|