class Storage { constructor(name) { this.name = 'storage'; } //設置緩存 setItem(params) { let obj = { name: '', value: '', expires: "", startTime: new Date().getTime(),//記錄何時將值存入緩存,毫秒級 endTime: new Date().getTime()//記錄過期值,毫秒級 用於getItem知道什麼時間過期 } let options = {}; //將obj和傳進來的params合併 Object.assign(options, obj, params); options.endTime = options.startTime +options.expires; if (options.expires) { //如果options.expires設置了的話 //以options.name爲key,options爲值放進去 localStorage.setItem(options.name, JSON.stringify(options)); } else { //如果options.expires沒有設置,就判斷一下value的類型 let type = Object.prototype.toString.call(options.value); //如果value是對象或者數組對象的類型,就先用JSON.stringify轉一下,再存進去 if (Object.prototype.toString.call(options.value) == '[object Object]') { options.value = JSON.stringify(options.value); } if (Object.prototype.toString.call(options.value) == '[object Array]') { options.value = JSON.stringify(options.value); } localStorage.setItem(options.name, options.value); } } //拿到緩存 getItem(name) { let item = localStorage.getItem(name); //先將拿到的試着進行json轉爲對象的形式 try { item = JSON.parse(item); } catch (error) { //如果不行就不是json的字符串,就直接返回 item = item; } if (item) { //如果有startTime的值,說明設置了失效時間 if (item.startTime) { let date = new Date().getTime(); //何時將值取出減去剛存入的時間,與item.expires比較,如果大於就是過期了,如果小於或等於就還沒過期 if (date - item.startTime > item.expires) { //緩存過期,清除緩存,返回false localStorage.removeItem(name); return null; } else { let date = new Date(item.endTime);//時間戳爲10位需*1000,時間戳爲13位的話不需乘1000 let Y = date.getFullYear() + '-'; let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'; let D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' '; let h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':'; let m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) + ':'; let s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds()); item.endTime= Y + M + D + h + m + s; //緩存未過期,返回值 return item; } } else { //如果沒有設置失效時間,直接返回值 return item; } } else { return null; } } //移出緩存 removeItem(name) { localStorage.removeItem(name); } //移出全部緩存 clear() { localStorage.clear(); } }
前端緩存都沒有記錄緩存過期時間只能隨一些操作或者瀏覽器期限默認過期,實際開發中多有不便。看過一個關於緩存設置過期時間得文字,記錄下來。好好學習 好好記錄。
關於 Storage 得調用
let storage = new Storage(); //添加 var sd = storage.getItem("_sd"); //獲取 storage.setItem({ name: "lcs",//key value: "",//key對應值 不僅僅能存字符串 對象數組也可以哦 可以自己實驗實驗 expires: 60000 * 30//過期時間 當前時間加上expires }); //刪除 var sd = storage.removeItem("_sd") //全部移除 var sd = storage.clear()
上面是針對localStorage進行緩存得 ,如果需要用sessionStorage緩存 講JS文件中得名稱替換即可
關於localStorage和sessionStorage
相同點:
1:都是用來存儲客戶端臨時信息的對象。
2:只能存儲字符串類型的對象
3:使用相同的API: setItem方法設置
不同點:
1:localStorage生命週期是永久,sessionstorage生命週期爲當前窗口或標籤頁
2:相同瀏覽器的不同頁面間可以共享相同的 localStorage(頁面屬於相同域名和端口),但是不同頁面或標籤頁間無法共享sessionStorage的信息。這裏需要注意的是,頁面及標 籤頁僅指頂級窗口,如果一個標籤頁包含多個iframe標籤且他們屬於同源頁面