全局数据持久化封装

功能介绍

实现全局数据共享,刷新数据不丢失

使用方法

首页面加载 persist.js 并写入下面代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
((function () {
const userInfo = {};
const stationInfo = {};
const alarm = {};
const actionRecord = {};

$solway.persist({
userInfo,
stationInfo,
alarm,
actionRecord,
});

// $solway.getStore(); 获取
// $solway.setStore('userInfo', {}); 设置
})());

实现

persist.js

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
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.$solway = global.$solway || {})));
}(window, ((exports) => {
const win = window;
let store = {};
const persist = obj => {
const persistStr = win.localStorage.persist;

if (obj === void 0) return store;

if (!(typeof obj == 'object' && obj)) return console.error('不是一个合法的json,数据持久失败');

if (obj.__set__) {
delete obj.__set__;
win.localStorage.persist = JSON.stringify(obj);
return store = obj;
}

if (persistStr) {
const o = JSON.parse(persistStr);
if (!(typeof o == 'object' && o)) return console.error('数据被损坏');
return store = JSON.parse(persistStr);
}

win.localStorage.persist = JSON.stringify(obj);
return store = obj;

};


const setStore = (name, action) => {
if (typeof name !== 'string') return console.error('设置的存储名不是一个合法的key' + name);
if (!(typeof action == 'object' && action)) return console.error('设置的值不是一个合法的json' + action);
if (!store.hasOwnProperty(name)) return console.error('store中没有该项数据' + name);
const _store = {
...store,
[name]: action,
__set__: true
};
return $solway.persist(_store)[name];
};
const getStore = () => ({ ...store });

exports.persist = persist;
exports.setStore = setStore;
exports.getStore = getStore;
})));

坚持原创技术分享,您的支持将鼓励我继续创作!