• Tips: localStrorage 只能存简单的值类型

    9-1 设置获取缓存

    1. #设置缓存 localStorage.setItem("xx",xx);
    2. #获取缓存 localStorage.getItem("xx");
    1. var lists = [{name:"good"}];
    2. var res = JSON.stringify(lists);
    3. localStorage.setItem("todo",res);//设置缓存
    4. var result = localStorage.getItem("todo");//获取缓存
    5. console.log(JSON.parse(result));

    9-2 封装了localStorage

    ```javascript //utils/index.js function setStorage(key,value){ if(Array.isArray(value) || typeof value == “object”){
    1. localStorage.setItem(key,JSON.stringify(value));
    } else{
    1. 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; } }

  1. ```javascript
  2. //.html
  3. var lists = [{name:"html",state:false}];
  4. setStorage("todo",lists);
  5. var res = getStorage("todo");
  6. console.log(res);