1. localstorage
/**
* 用的是ES6的语法
* 存储localstorage
*/
const setStore = (name, content) => {
if (!name) return;
if (typeof content !== 'string') {
content = JSON.stringify(content);
}
window.localstorage.setItem(name, content);
}
/**
* 获取localstorage
*/
const getStore = name => {
if (!name) return;
return window.localstorage.getItem(name);
}
/**
* 删除localstorage
*/
const removeStore = name => {
if (!name) return;
window.localstorage.removeItem(name);
}
2. sessionstorage
/**
* 存储sessionStorage
*/
const setStore = (name, content) => {
if (!name) return;
if (typeof content !== 'string') {
content = JSON.stringify(content);
}
window.sessionStorage.setItem(name, content);
}
/**
* 获取sessionStorage
*/
const getStore = name => {
if (!name) return;
return window.sessionStorage.getItem(name);
}
/**
* 删除sessionStorage
*/
const removeStore = name => {
if (!name) return;
window.sessionStorage.removeItem(name);
}
3. cookie
/**
* 存储cookie
*/
const setCookie = (name,value) =>{
var Days = 10;
var exp = new Date();
exp.setTime(exp.getTime() + Days*24*60*60*1000);
document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString()+";path=/;";
}
/**
* 获取cookie
*/
const getCookie = (name) =>{
var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
if(arr=document.cookie.match(reg))
return unescape(arr[2]);
else
return null;
}
/**
* 删除cookie
*/
const delCookie = (name) =>{
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval=getCookie(name);
if(cval!=null)
document.cookie= name + "="+cval+";expires="+exp.toGMTString()+";path=/;";
}