兼容 Cookie
和 localStorage
两种方式,且都可设置过期时限;
名称 | 类型 | 描述 |
---|---|---|
type | String | 存储方式。支持 2 种类型:cookie(存储值最大为 4KB)、localStorage(存储值最大为 5M) |
timeOut | Number | 过期时限。单位为小时,例如 7 * 24 为 7 天 |
Boolean
,true
表示初始化成功,false
表示已初始化;
初始化方法 Storage.init
,仅第一次生效;
// 初始化为 localStorage 类型,7 天过期
Storage.init('localStorage', 7 * 24);
名称 | 类型 | 描述 |
---|---|---|
key | String | 唯一标识 |
val | Object | 存储值 |
null
;名称 | 类型 | 描述 |
---|---|---|
key | String | 唯一标识 |
Boolean
,true
成功,false
失败;名称 | 类型 | 描述 |
---|---|---|
key | String | 唯一标识 |
Boolean
,true
存在,false
过期或移除;名称 | 类型 | 描述 |
---|---|---|
key | String | 唯一标识 |
此处使用 Vue2.x
<template>
<div>
<button @click="onclick(0)">存储</button>
<button @click="onclick(1)">获取</button>
<button @click="onclick(2)">删除</button>
<button @click="onclick(3)">清空</button>
<button @click="onclick(4)">获取keys</button>
</div>
</template>
<script>
import Storage from '../js/Storage'
export default {
methods: {
onclick(i) {
switch (i) {
case 0: {
Storage.set('my_test', true);
break;
}
case 1: {
let val = Storage.get('my_test', false);
console.log('my_test', val);
break;
}
case 2: {
Storage.remove('my_test');
break;
}
case 3: {
Storage.clear();
break;
}
case 4: {
let keys = Storage.getKeys();
console.log('keys', keys);
break;
}
default:
break;
}
}
},
mounted() {
// 初始化
Storage.init('localStorage');
// Storage.init('cookie');
}
}
</script>
文件 Storage.js
,文件分三部分 MyCookie
、MyLocalStorage
和 Storage
;
// 唯一key
const MY_KEYS = '_My_Storage_Keys'
class MyCookie {
constructor() {
this.keys = [MY_KEYS]
this.lastTime = null
let flag = false
let name = `${MY_KEYS}=`
let ca = document.cookie.split(';')
for (let i = 0; i < ca.length; i++) {
let c = ca[i].trim()
if (c.indexOf(name) == 0)
flag = true
}
this.keys = flag ? this.get(MY_KEYS) : []
}
getKeys() {
return this.keys
}
setHistory(timeOut) {
timeOut = timeOut || this.lastTime
let d = new Date()
d.setTime(d.getTime() + (timeOut * 60 * 60 * 1000))
let expires = 'expires=' + d.toGMTString()
document.cookie = `${MY_KEYS}=` + JSON.stringify({ data: this.keys }) + '; ' + expires
this.lastTime = timeOut
}
set(key, val, timeOut) {
let d = new Date()
d.setTime(d.getTime() + (timeOut * 60 * 60 * 1000))
let expires = 'expires=' + d.toGMTString()
document.cookie = key + '=' + JSON.stringify({ data: val }) + '; ' + expires
this.keys.indexOf(key) < 0 && this.keys.push(key) && this.setHistory(timeOut)
}
get(key) {
if (!this.exist(key))
return null
let name = key + '='
let ca = document.cookie.split(';')
for (let i = 0; i < ca.length; i++) {
let c = ca[i].trim()
if (c.indexOf(name) === 0)
return JSON.parse(c.substring(name.length, c.length)).data
}
}
remove(key) {
for (let i in this.keys) {
if (key == this.keys[i]) {
document.cookie = this.keys[i] + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT'
this.keys.splice(i, 1)
this.setHistory()
return true
}
}
return false
}
exist(key) {
let name = key + '='
let ca = document.cookie.split(';')
for (let i = 0; i < ca.length; i++) {
let c = ca[i].trim()
if (c.indexOf(name) === 0)
return true
}
this.remove(key)
return this.keys.indexOf(key) > -1
}
clear() {
for (let i in this.keys) {
document.cookie = this.keys[i] + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT'
}
this.keys = [MY_KEYS]
this.setHistory(0)
}
}
class MyLocalStorage {
constructor() {
this.keys = [MY_KEYS];
this.keys = localStorage.getItem(MY_KEYS) ? this.get(MY_KEYS) : [];
for (let i in this.keys) {
this.exist(this.keys[i]);
}
}
getKeys() {
return this.keys;
}
setHistory() {
localStorage.setItem(MY_KEYS, JSON.stringify({ data: this.keys })) //转换成json字符串序列
}
set(key, val, timeOut) {
let cur = new Date().getTime()
localStorage.setItem(key, JSON.stringify({ data: val, time: cur, timeOut: timeOut })) //转换成json字符串序列
this.keys.indexOf(key) < 0 && this.keys.push(key) && this.setHistory()
}
get(key) {
if (!this.exist(key))
return null
let val = localStorage.getItem(key) //获取存储的元素
let dataObj = JSON.parse(val) //解析出json对象
if (dataObj.timeOut != null && (new Date().getTime() - dataObj.time > dataObj.timeOut * 60 * 60 * 1000)) //如果当前时间-减去存储的元素在创建时候设置的时间 > 过期时间
{
return null
} else {
return dataObj.data
}
}
remove(key) {
for (let i in this.keys) {
if (key == this.keys[i]) {
localStorage.removeItem(this.keys[i])
this.keys.splice(i, 1)
this.setHistory()
return true
}
}
return false
}
exist(key) {
let val = localStorage.getItem(key) //获取存储的元素
let dataObj = JSON.parse(val) //解析出json对象
if (dataObj && dataObj.timeOut != null && (new Date().getTime() - dataObj.time > dataObj.timeOut * 60 * 60 * 1000)) //如果当前时间-减去存储的元素在创建时候设置的时间 > 过期时间
{
this.remove(key)
}
return this.keys.indexOf(key) > -1
}
clear() {
for (let i in this.keys) {
localStorage.removeItem(this.keys[i])
}
this.keys = [MY_KEYS]
this.setHistory()
}
}
class Storage {
static init(type, timeOut) {
// 仅初始化一次
if (this.currentStorage) {
return false;
}
this.type = type;
this.timeOut = timeOut;
this.storageFactory = {
cookie: MyCookie,
localStorage: MyLocalStorage,
}
this.currentStorage = new this.storageFactory[type]();
return true;
}
static getKeys() {
return this.currentStorage.getKeys()
}
static set(key, val) {
this.currentStorage.set(`_My_Storage_${key}`, val, this.timeOut)
}
static get(key) {
return this.currentStorage.get(`_My_Storage_${key}`);
}
static remove(key) {
return this.currentStorage.remove(`_My_Storage_${key}`);
}
static exist(key) {
return this.currentStorage.exist(`_My_Storage_${key}`);
}
static clear() {
this.currentStorage.clear();
}
}
export default Storage