localStorage二次封装
图示:
安装: npm i --save-dev crypto-js
storage.ts
import CryptoJS from "crypto-js";
interface globalConfig {
type: "localStorage" | "sessionStorage";
prefix: string;
expire: number;
isEncrypt: boolean;
}
const config: globalConfig = {
type: "localStorage", //存储类型,localStorage | sessionStorage
prefix: "goto_w", //版本号
expire: 24 * 60, //过期时间,默认为一天,单位为分钟
isEncrypt: true, //支持加密、解密数据处理
};
// 对 crypto-js 设置密钥和密钥偏移量,可以采用将一个私钥经 MD5 加密生成16位密钥获得
const SECRET_KEY = CryptoJS.enc.Utf8.parse("3333e6e143439161"); //十六位十六进制数作为密钥
const SECRET_IV = CryptoJS.enc.Utf8.parse("e3bbe7e3ba84431a"); //十六位十六进制数作为密钥偏移量
// 加密
const encrypt = (data: object | string): string => {
//加密
if (typeof data === "object") {
try {
data = JSON.stringify(data);
} catch (e) {
throw new Error("encrypt error" + e);
}
}
const dataHex = CryptoJS.enc.Utf8.parse(data);
const encrypted = CryptoJS.AES.encrypt(dataHex, SECRET_KEY, {
iv: SECRET_IV,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
return encrypted.ciphertext.toString();
};
// 解密
const decrypt = (data: string) => {
//解密
const encryptedHexStr = CryptoJS.enc.Hex.parse(data);
const str = CryptoJS.enc.Base64.stringify(encryptedHexStr);
const decrypt = CryptoJS.AES.decrypt(str, SECRET_KEY, {
iv: SECRET_IV,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
return decryptedStr.toString();
};
// setStorage 设置值
const setStorage = (
key: string,
value: any,
expire: number = 24 * 60
): boolean => {
//设定值
if (value === "" || value === null || value === undefined) {
//空值重置
value = null;
}
if (isNaN(expire) || expire < 0) {
//过期时间值合理性判断
throw new Error("Expire must be a number");
}
const data = {
value, //存储值
time: Date.now(), //存储日期
expire: Date.now() + 1000 * 60 * expire, //过期时间
};
//是否需要加密,判断装载加密数据或原数据
window[config.type].setItem(
autoAddPreFix(key),
config.isEncrypt ? encrypt(JSON.stringify(data)) : JSON.stringify(data)
);
return true;
};
// 根据key获取value
const getStorageFromKey = (key: string) => {
//获取指定值
if (config.prefix) {
key = autoAddPreFix(key);
}
if (!window[config.type].getItem(key)) {
//不存在判断
return null;
}
const storageVal = config.isEncrypt
? JSON.parse(decrypt(window[config.type].getItem(key) as string))
: JSON.parse(window[config.type].getItem(key) as string);
const now = Date.now();
if (now >= storageVal.expire) {
//过期销毁
removeStorageFromKey(key);
return null;
//不过期回值
} else {
return storageVal.value;
}
};
// 获取所有存储值
const getAllStorage = () => {
//获取所有值
const storageList: any = {};
const keys = Object.keys(window[config.type]);
const formatted = keys.map(keyword => keyword.replace(/^goto_w_/, ''))
formatted.forEach((key) => {
const value = getStorageFromKey(key);
if (value !== null) {
//如果值没有过期,加入到列表中
storageList[key] = value;
}
});
return storageList;
};
// 获取存储值数量
const getStorageLength = () => {
//获取值列表长度
return window[config.type].length;
};
// 根据key删除存储值
const removeStorageFromKey = (key: string) => {
//删除值
if (config.prefix) {
key = autoAddPreFix(key);
}
window[config.type].removeItem(key);
};
// 清空存储列表
const clearStorage = () => {
window[config.type].clear();
};
// 基于全局配置的prefix参数添加前缀
const autoAddPreFix = (key: string) => {
//添加前缀,保持浏览器Application视图唯一性
const prefix = config.prefix || "";
return `${prefix}_${key}`;
};
// 导出函数列表
export {
setStorage,
getStorageFromKey,
getAllStorage,
getStorageLength,
removeStorageFromKey,
clearStorage,
};
使用实例:
<template>
<div>
<button @click="setStorageClick">设置存储</button>
<button @click="viewStorageClick">读取存储</button>
<button @click="removeStorageClick">移除存储</button>
</div>
</template>
<script setup lang="ts">
import {
setStorage,
getStorageFromKey,
getAllStorage,
getStorageLength,
removeStorageFromKey,
clearStorage
} from '@/utils/storage.js'
const setStorageClick = () => {
setStorage('name', '忆往昔', 1)
setStorage('age', { now: 18 }, 1000)
setStorage('history', [1, 2, 3], 1000)
}
const viewStorageClick = () => {
console.log(getStorageFromKey('name'))
console.log(getStorageFromKey('age'))
console.log(getStorageFromKey('history'))
console.log(getStorageLength());
console.log(getAllStorage());
}
const removeStorageClick = () => {
removeStorageFromKey('name')
removeStorageFromKey('age')
removeStorageFromKey('history')
// clearStorage();
}
</script>