Storage封裝
Cookie,localStorage,sessionStorage三者的區別?
- 共同點:都是保存在瀏覽器端、且同源的
- cookie數據始終在同源的http請求中攜帶(即使不需要),cookie在瀏覽器和服務器間來回傳遞;而sessionStorage和localStorage不會自動把數據發送給服務器,僅在本地保存。
- cookie數據還有路徑限制,storage只存儲在域名下。
- 存儲大小:Cookie 4kb; storage 5M
- 有效期: sessionStorage:僅在當前瀏覽器窗口關閉之前有效;
localStorage:始終有效,窗口或瀏覽器關閉也一直保存,因此用作持久數據;
cookie:只在設置的cookie過期時間之前有效,即使窗口關閉或瀏覽器關閉 。
6.Cookie沒有特定的API,而storage有
爲什麼要封裝Storage?
- Storage本身有API,但只是簡單的鍵值對
- Storage只存儲字符串,需要人工轉換爲json對象
- Storage只能一次性清空,不能單個清空
Ctrl+Shift+I,Application
/*
*Storage封裝
*/
const STORAGE_KEY = "mall";
export default{
//存儲值
setItem(key,value,module_name){
if (module_name) {
let val = this.getItem(module_name);
val[key] = value;
this.setItem(module_name,val)
}else{
let val = this.getStorage();
val[key] = value;
window.sessionStorage.setItem(STORAGE_KEY,JSON.stringify(val));
}
},
//獲取某一模塊下面的屬性
getItem(key,module_name){
if (module_name) {
let val = this.getItem(); //返回一個Object
if (val) {
return val[key];
}
}
return this.getStorage()[key];
},
getStorage(){
return JSON.parse(window.sessionStorage.getItem(STORAGE_KEY) || '{}')
},
clear(key,module_name){
let val = this.getStorage();
if (module_name){
delete val[module_name][key];
} else {
delete val[key];
}
window.sessionStorage.setItem(STORAGE_KEY,JSON.stringify(val));
}
}
然後再在APP.vue中import導入,再在mounted方法中引用
import storage from "./storage/index"
mounted(){
storage.setItem('abnf',"1")
}