Skip to content

Commit 6f10f34

Browse files
localstoage扩展
1 parent cb4647e commit 6f10f34

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/**
2+
* created by csxiaoyao
3+
* localstorage 扩展
4+
* 2019.01.14
5+
*/
6+
class csxiaoyaoStorage {
7+
/*
8+
* set 存储方法
9+
* @ param {String} key 键
10+
* @ param {String} value 值
11+
* @ param {String} expired (可选)过期时间(min)
12+
*/
13+
static set (key, value, expired = 0) {
14+
if (!window.localStorage) {
15+
return false
16+
}
17+
const data = JSON.stringify(value)
18+
const expireKey = `${key}__expires__`
19+
const expireTime = Date.now() + 1000 * 60 * expired
20+
try {
21+
window.localStorage.setItem(key, data)
22+
if (expired) {
23+
window.localStorage.setItem(expireKey, expireTime)
24+
}
25+
return true
26+
} catch (e) {
27+
if (e.name === 'QuotaExceededError') {
28+
window.localStorage.clear()
29+
window.localStorage.setItem(key, data)
30+
return true
31+
}
32+
return false
33+
}
34+
}
35+
/*
36+
* get 获取方法
37+
* @ param {String} key 键
38+
*/
39+
static get (key) {
40+
if (!window.localStorage) {
41+
return false
42+
}
43+
const now = Date.now()
44+
const expired = window.localStorage.getItem(`${key}__expires__`) || Date.now + 1
45+
if (now >= expired) {
46+
this.del(key)
47+
return false
48+
}
49+
const value = window.localStorage[key] ? JSON.parse(window.localStorage.getItem(key)) : window.localStorage.getItem(key)
50+
return value
51+
}
52+
/*
53+
* del 删除方法
54+
* @ param {String} key 键
55+
*/
56+
static del (key) {
57+
if (!window.localStorage) {
58+
return false
59+
}
60+
window.localStorage.removeItem(key)
61+
window.localStorage.removeItem(`${key}__expires__`)
62+
return true
63+
}
64+
}
65+
66+
export default lubanStorage

0 commit comments

Comments
 (0)