localStorage.setItem("key","value");//存數據 localStorage.getItem("key");//取數據 localStorage.removeItem("key");//刪除數據 localStorage.clear();//清空數據
sessionStorage使用用法和localStorage同樣緩存
sessionStorage是會話緩存session
localStorage是持久緩存spa
這裏簡單封裝了一個,默認緩存7天,獲取數據時判斷數據是否過時code
/** * 設置緩存數據 * 默認緩存一個星期 * @param key * @param value * @param exp 緩存時間(d天數,h小時,m分鐘,s秒【例:7d=7天,7h=7小時,7m=7分鐘】) */ function lStorage_set(key,value,exp) { var timestamp = new Date().getTime(); if(typeof exp != "undefined"){ if (endWith(exp,'d')) { exp = timestamp + parseInt(exp.replace('d','')) * 1000 * 60 * 60 * 24; } else if(endWith(exp,'h')){ exp = timestamp + parseInt(exp.replace('h', '')) * 1000 * 60 * 60; } else if (endWith(exp, 'm')) { exp = timestamp + parseInt(exp.replace('m', '')) * 1000 * 60; } else if (endWith(exp, 's')) { exp = timestamp + parseInt(exp.replace('s', '')) * 1000; } else { exp = timestamp + exp; } }else{
exp = timestamp + (1000 * 60 * 60 * 24 * 7);
} localStorage.setItem(key, JSON.stringify({data: value, exp: exp})); } /** * 獲取緩存數據 * @param key * @returns {null} */ function lStorage_get(key) { var data = localStorage.getItem(key); if(data == null){ return null; } var timestamp = new Date().getTime(); var dataObj = JSON.parse(data); if(timestamp < dataObj.exp){ return dataObj.data; }else{ localStorage.removeItem(key); return null; } }
/** * 判斷data結尾是不是end * @param data * @param end * @returns {boolean} */ function endWith(data,end){ var d = data.length - end.length; return (d >= 0 && data.lastIndexOf(end) == d); }