分为localStorage和sessionStorage,一个永久有效,一个session级别的,用法完全相同;每个网站5M,用于存储字符串(只能存字符串)。
支持情况
检测
1 | if(window.localStorage){ |
使用
推荐统一使用setItem getItem removeItem
赋值方法
1 | localStorage.a = 3;//设置a为"3" |
取值方法
1 | var a1 = localStorage["a"];//获取a的值 |
异常处理
异常处理很重要,否则会出现莫名其妙得卡死,还不知道问题出在哪里)
主要是存储已满异常,可以考虑使用LRU(Least Recently Used最近最少使用)
1 | try{ |
封装
如下是项目中使用的一个简单封装,storage.js,es6语法。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
50
51
52
53
54
55
56
57
58
59
60
61/**
* 本地存储封装,项目中其他地方不要直接使用localStorage和sessionStorage,统一使用封装。
* 简化接口,字符串json转换。
* 如果本地存储使用比较多,可以考虑封装LRU(Least Recently Used最近最少使用)
*/
export default {
global: {
get(key) {
return window.globalStorage ? window.globalStorage[key] : null;
},
set(key, jsonValue) {
window.globalStorage = window.globalStorage ? window.globalStorage : {};
window.globalStorage[key] = jsonValue;
},
remove(key) {
if (window.globalStorage) {
delete window.globalStorage[key];
}
},
removeAll() {
window.globalStorage = {};
},
},
local: {
get(key) {
const strValue = localStorage.getItem(key);
return JSON.parse(strValue);
},
set(key, jsonValue) {
const strValue = JSON.stringify(jsonValue);
localStorage.setItem(key, strValue);
},
remove(key) {
localStorage.removeItem(key);
},
removeAll() {
localStorage.clear();
},
},
session: {
get(key) {
const strValue = sessionStorage.getItem(key);
return JSON.parse(strValue);
},
set(key, jsonValue) {
const strValue = JSON.stringify(jsonValue);
sessionStorage.setItem(key, strValue);
},
remove(key) {
sessionStorage.removeItem(key);
},
removeAll() {
sessionStorage.clear();
},
},
};
// 使用
import Storage from './storage.js';
Storage.session.get(key);
Storage.session.set(key, jsonValue);
参考链接:
http://www.cnblogs.com/xiaowei0705/archive/2011/04/19/2021372.html