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 = Object.assign({}, options, {
|
19 | storage: options.storage || 'local',
|
20 | name: options.name || 'ls',
|
21 | });
|
22 |
|
23 | if (_options.storage && ['memory', 'local', 'session'].indexOf(_options.storage) === -1) {
|
24 | throw new Error(`Vue-ls: Storage "${_options.storage}" is not supported`);
|
25 | }
|
26 |
|
27 | let store = null;
|
28 |
|
29 | switch(_options.storage) {
|
30 | case 'local':
|
31 | store = 'localStorage' in _global
|
32 | ? _global.localStorage
|
33 | : null
|
34 | ;
|
35 | break;
|
36 |
|
37 | case 'session':
|
38 | store = 'sessionStorage' in _global
|
39 | ? _global.sessionStorage
|
40 | : null
|
41 | ;
|
42 | break;
|
43 | case 'memory': store = MemoryStorage;
|
44 | break;
|
45 | }
|
46 |
|
47 | if (!store) {
|
48 | store = MemoryStorage;
|
49 |
|
50 | console.error(`Vue-ls: Storage "${_options.storage}" is not supported your system, use memory storage`);
|
51 | }
|
52 |
|
53 | const ls = new WebStorage(store);
|
54 |
|
55 | ls.setOptions(Object.assign(ls.options, {
|
56 | namespace: '',
|
57 | }, _options || {}));
|
58 |
|
59 | Vue[_options.name] = ls;
|
60 | Object.defineProperty(Vue.prototype, `$${_options.name}`, {
|
61 | |
62 |
|
63 |
|
64 |
|
65 |
|
66 | get() {
|
67 | return ls;
|
68 | },
|
69 | });
|
70 | },
|
71 | };
|
72 |
|
73 | _global.VueStorage = VueStorage;
|
74 |
|
75 | export default VueStorage;
|