1、localstorage存取:
export const Storage = {
storage: window.localStorage,
set(item, value) {
if (typeof value === "object") {
value = JSON.stringify(value);
}
return this.storage.setItem(item, value);
},
get(item) {
const itemStr = this.storage.getItem(item);
if (itemStr) {
try {
return JSON.parse(itemStr)
} catch(err) {
return itemStr
}
// return JSON.parse(itemStr);
} else {
return null;
}
},
remove(item) {
return this.storage.removeItem(item);
},
clear() {
return this.storage.clear();
},
keys() {
let arr = [];
for (let i = 0; i < window.localStorage.length; i++) {
arr.push(window.localStorage.key(i));
}
return arr;
}
};
2、cookie存取、设置过期时间
export const Cookie = {
get(name) {
const reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
let arr = document.cookie.match(reg);
if (arr) {
return decodeURIComponent(arr[2]);
} else {
return null;
}
},
set(name, value, time) {
/*
* 取时函数
* 这是有设定过期时间的使用示例:
* s是指秒,如20秒则是:s20
* h是指时,如12小时则是:h12
* d是指天,如30天则:d30
* */
const getsec = str => {
const str1 = str.substring(1, str.length) * 1;
const str2 = str.substring(0, 1);
return {'s':str1 * 1000, 'h':str1 * 60 * 60 * 1000, 'd':str1 * 24 * 60 * 60 * 1000}[str2];
};
if (!time) {
const Days = 30;
const exp = new Date();
exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + "; path=/";
} else {
const strsec = getsec(time);
const exp = new Date();
exp.setTime(exp.getTime() + strsec * 1);
document.cookie = name + "=" + encodeURIComponent(value) + ";expires=" + exp.toGMTString() + "; path=/";
}
},
remove(name) {
const exp = new Date();
exp.setTime(exp.getTime() - 1);
const cval = this.get(name);
if (cval !== null)
document.cookie = name + "=" + encodeURIComponent(cval) + ";expires=" + exp.toGMTString() + "; path=/";
}
};
网友评论