cookie,local,session操作
emer 发布于 2020-11-26 11:29 1660 次阅读
<pre class="prettyprint lang-js linenums" background:#000;>
class Storage {
// constructor(options) { } constructor() {
console.log('constructor')
}
// 获取_key的数据 => { data, keyInfo } _getData(_key) {
console.log('调用了get')
let _keys = Array.isArray(_key) ? _key : [_key]
_keys.forEach(() => {
return JSON.parse(localStorage.getItem())
});
}
//移除操作 _remove(_key) {
let _keys = Array.isArray(_key) ? _key : [_key]
_keys.forEach(() => {
localStorage.removeItem();
});
}
//设置操作 set(key, data, options = {}) {
console.log('调用了set')
const _key = this._getKey(key);
const _data = JSON.stringify(data, options);
localStorage.setItem(_key, _data);
}
// 是否有效期内 _isExpired(_key) {
const { keyInfo } = this._getData(_key);
const { expires, timestamp } = keyInfo;
if (!expires) {
return true;
}
return (
timestamp + expires * 24 * 3600 * 1000 - new Date().getTime() < 0 );
}
} class Cookie {
setCookie(name, value, n) {
var oDate = new Date();
oDate.setDate(oDate.getDate() + n);
document.cookie = name + "=" + value + ";expires=" + oDate;
}
getCookie(name) {
var str = document.cookie;
var arr = str.split("; ");
for (var i = 0; i < arr.length; i++) {
//console.log(arr[i]); var newArr = arr[i].split("=");
if (newArr[0] == name) {
return newArr[1];
}
}
}
removeCookie(name) {
this.setCookie(name, 1, -1);
}
} class Session {
get(key) {
let keys = Array.isArray(key) ? key : [key]
keys.forEach((r) => {
return JSON.parse(sessionStorage[r])
});
}
set(key, value) {
var data = {
value: value
}
sessionStorage[key] = JSON.stringify(data);
}
// 删除 remove(key) {
let keys = Array.isArray(key) ? key : [key]
keys.forEach((r) => {
return JSON.parse(sessionStorage.removeItem[r])
});
}
// 清除全部 clear() {
sessionStorage.clear();
}
} export { Storage, Cookie, Session };
这里把他们放进一个文件中,然后把他们类名暴露出去,我们再看看如何使用
const local = new _Storage()
local.set("name", { name: "SuperIron" }, { expires: 1 });
const Info = local.get('name')