- Tips: localStrorage 只能存简单的值类型
9-1 设置获取缓存
#设置缓存 localStorage.setItem("xx",xx);
#获取缓存 localStorage.getItem("xx");
var lists = [{name:"good"}];
var res = JSON.stringify(lists);
localStorage.setItem("todo",res);//设置缓存
var result = localStorage.getItem("todo");//获取缓存
console.log(JSON.parse(result));
9-2 封装了localStorage
```javascript //utils/index.js function setStorage(key,value){ if(Array.isArray(value) || typeof value == “object”){
} else{localStorage.setItem(key,JSON.stringify(value));
} }localStorage.setItem(key,value);
function getStorage(key){ let value = localStorage.getItem(key); // 正则表达式—使用正则去判断数组和对象(对象和数组才能用JSON.parse) {…} […] // .所有的字符 +大于等于一位 var reg = /^[{[].+[]}]$/; if(reg.test(value)){ return JSON.parse(value); } else{ return value; } }
```javascript
//.html
var lists = [{name:"html",state:false}];
setStorage("todo",lists);
var res = getStorage("todo");
console.log(res);