The difference between Cookie, localStorage and sessionStorage
Storage size: Cookie4K, Storage5M
Validity period: Cookie has a validity period, and Storage is permanently stored
Cookie will be sent to the server and stored in the memory, Storage is only stored in the browser
Path: Cookie has path restriction, Storage is only stored under domain name
API: Cookie has no specific API, Storage has corresponding API
Why encapsulate Storage
Storage itself has API, but the key/value form of knowledge is simple
Storage only stores strings and needs to be manually converted into json objects
Storage can only be emptied once, not individually
Example
// Storage 封装constSTORAGE_KET='mall'exportdefault{
// 存储值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_KET,JSON.stringify(val))}let val =this.getStorage();
val[key]= value;
window.sessionStorage.setItem(STORAGE_KET,JSON.stringify(val))},// 获取某一个模块下面的属性 user 下面的 userNamegetItem(key,module_name){
if(module_name){
let val =this.getItem(module_name);if(val)return val[key];}this.getStorage()[key]},getStorage(){
returnJSON.parse(window.sessionStorage.getItem(STORAGE_KET)||'{}')},clear(key,module_name){
let val =this.getItem();if(module_name){
delete val[module_name][key];}else{
delete val[key];}this.setItem(STORAGE_KET,val)}}