Skip to content

Commit 24efca5

Browse files
committed
本地存储
1 parent ebd9a48 commit 24efca5

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

src/utils/storage.js

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
2+
class LocalStorage {
3+
constructor (prefix = 'web') {
4+
this.prefix = prefix;
5+
}
6+
7+
/**
8+
* @param {type}
9+
* @return:
10+
* @Description:获取本地存储的方法
11+
* @Author: 水痕
12+
* @LastEditors: 水痕
13+
* @Date: 2019-08-16 13:30:46
14+
*/
15+
getItem (key) {
16+
key = this.getKey(key);
17+
const storeData = window.localStorage.getItem(key);
18+
if (storeData) {
19+
const {
20+
value,
21+
options: { storeTime },
22+
} = JSON.parse(storeData);
23+
// 如果从存储中获取的时间大于当前的时间或者等于0的时候表示当前的localStorage有效
24+
if (storeTime > new Date().getTime()) {
25+
return value;
26+
} else {
27+
this.removeItem(key);
28+
return null;
29+
}
30+
}
31+
return null;
32+
}
33+
34+
/**
35+
* @param {type}
36+
* @return:
37+
* @Description: 设置存储
38+
* @Author: 水痕
39+
* @LastEditors: 水痕
40+
* @Date: 2019-08-16 13:31:00
41+
*/
42+
setItem (key, value, time) {
43+
key = this.getKey(key);
44+
// 如果用户没传递时间进来就是一天
45+
try {
46+
time = new Date(time).getTime() || time.getTime();
47+
} catch (e) {
48+
time = new Date().getTime() + 1000 * 60 * 60 * 24 * 1;
49+
}
50+
const options = {
51+
storeTime: time,
52+
prefix: this.prefix,
53+
};
54+
window.localStorage.setItem(key, JSON.stringify({ value, options }));
55+
}
56+
57+
/**
58+
* @param {type}
59+
* @return:
60+
* @Description: 删除存储
61+
* @Author: 水痕
62+
* @LastEditors: 水痕
63+
* @Date: 2019-08-16 13:31:11
64+
*/
65+
removeItem (key) {
66+
key = this.getKey(key);
67+
const value = this.getItem(key);
68+
if (value) {
69+
window.localStorage.removeItem(key);
70+
}
71+
}
72+
73+
/**
74+
* @param {type}
75+
* @return:
76+
* @Description: 私有方法获取key
77+
* @Author: 水痕
78+
* @LastEditors: 水痕
79+
* @Date: 2019-08-16 13:31:22
80+
*/
81+
getKey (key) {
82+
return `${this.prefix}:${key}`;
83+
}
84+
}
85+
86+
export const storage = new LocalStorage('sea');

0 commit comments

Comments
 (0)