forked from gauseen/tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage.js
43 lines (41 loc) · 952 Bytes
/
storage.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
// 新建 storage 对象
/**
* @param {String} type 本地存储类型 sessionStorage | localStorage (default)
* @param {String} key 本地存储的键
* @param {Any} value 本地存储的值
*
* e.g.
* 存储 storage().set('nameKey', 'gauseen')
* 取值 storage().get('nameKey')
* 清空所有 storage().clearAll()
* 清空 storage().clearItem('nameKey')
*/
import typer from './typer'
export default function storage (type = 'localStorage') {
let storageType = type
return {
get (key) {
var value = window[storageType].getItem(key)
if (value) {
try {
return JSON.parse(value)
} catch (e) {
return value
}
}
return null
},
set (key, value) {
if (value && typer(value) === 'object') {
value = JSON.stringify(value)
}
window[storageType].setItem(key, value)
},
clearAll () {
window[storageType].clear()
},
clearItem (key) {
window[storageType].removeItem(key)
},
}
}