当前位置:   article > 正文

localStorage的高阶用法_window.localstorage.remove

window.localstorage.remove

原文:https://mp.weixin.qq.com/s/VBTAWVMAUq822dwNA1A2kg


const config = {
    type: 'localStorage', // 本地存储类型 localStorage/sessionStorage
    prefix: 'SDF_0.0.1', // 名称前缀 建议:项目名 + 项目版本
    expire: 1, //过期时间 单位:秒
    isEncrypt: true // 默认加密 为了调试方便, 开发过程中可以不加密
}

/**
 * title: storage.js
 * Desc: 对存储的简单封装
 * import {isSupportStorage, hasStorage, setStorage,getStorage,getStorageKeys,getStorageForIndex,getStorageLength,removeStorage,getStorageAll,clearStorage} from '@/utils/storage'
 * 安装crypto-js
 * npm install crypto-js
 * 引入 crypto-js 有以下两种方式
 * import CryptoJS from "crypto-js"; 或者 const CryptoJS = require("crypto-js");
 */

import CryptoJS from 'crypto-js';

// 十六位十六进制数作为密钥
const SECRET_KEY = CryptoJS.enc.Utf8.parse("3333e6e143439161");
// 十六位十六进制数作为密钥偏移量
const SECRET_IV = CryptoJS.enc.Utf8.parse("e3bbe7e3ba84431a");

// 类型 window.localStorage,window.sessionStorage,
const config = {
	type: 'localStorage', // 本地存储类型 sessionStorage
	prefix: 'SDF_0.0.1', // 名称前缀 建议:项目名 + 项目版本
	expire: 1, //过期时间 单位:秒
	isEncrypt: true // 默认加密 为了调试方便, 开发过程中可以不加密
}

// 判断是否支持 Storage
export const isSupportStorage = () => {
	return (typeof(Storage) !== "undefined") ? true : false
}

// 设置 setStorage
export const setStorage = (key, value, expire = 0) => {
	if (value === '' || value === null || value === undefined) {
		value = null;
	}

	if (isNaN(expire) || expire < 0) throw new Error("Expire must be a number");

	expire = (expire ? expire : config.expire) * 1000;
	let data = {
		value: value, // 存储值
		time: Date.now(), //存值时间戳
		expire: expire // 过期时间
	}

	const encryptString = config.isEncrypt ?
		encrypt(JSON.stringify(data)) :
		JSON.stringify(data);

	window[config.type].setItem(autoAddPrefix(key), encryptString);
}

// 获取 getStorage
export const getStorage = (key) => {
	key = autoAddPrefix(key);
	// key 不存在判断
	if (!window[config.type].getItem(key) || JSON.stringify(window[config.type].getItem(key)) === 'null') {
		return null;
	}

	// 优化 持续使用中续期
	const storage = config.isEncrypt ?
		JSON.parse(decrypt(window[config.type].getItem(key))) :
		JSON.parse(window[config.type].getItem(key));

	let nowTime = Date.now();

	// 过期删除
	if (storage.expire && config.expire * 6000 < (nowTime - storage.time)) {
		removeStorage(key);
		return null;
	} else {
		// 未过期期间被调用 则自动续期 进行保活
		setStorage(autoRemovePrefix(key), storage.value);
		return storage.value;
	}
}

// 是否存在 hasStorage
export const hasStorage = (key) => {
	key = autoAddPrefix(key);
	let arr = getStorageAll().filter((item) => {
		return item.key === key;
	})
	return arr.length ? true : false;
}

// 获取所有key
export const getStorageKeys = () => {
	let items = getStorageAll()
	let keys = []
	for (let index = 0; index < items.length; index++) {
		keys.push(items[index].key)
	}
	return keys
}

// 根据索引获取key
export const getStorageForIndex = (index) => {
	return window[config.type].key(index)
}

// 获取localStorage长度
export const getStorageLength = () => {
	return window[config.type].length
}

// 获取全部 getAllStorage
export const getStorageAll = () => {
	let len = window[config.type].length // 获取长度
	let arr = new Array() // 定义数据集
	for (let i = 0; i < len; i++) {
		// 获取key 索引从0开始
		let getKey = window[config.type].key(i)
		// 获取key对应的值
		let getVal = window[config.type].getItem(getKey)
		// 放进数组
		arr[i] = {
			'key': getKey,
			'val': getVal,
		}
	}
	return arr
}

// 删除 removeStorage
export const removeStorage = (key) => {
	window[config.type].removeItem(autoAddPrefix(key));
}

// 清空 clearStorage
export const clearStorage = () => {
	window[config.type].clear();
}

// 名称前自动添加前缀
const autoAddPrefix = (key) => {
	const prefix = config.prefix ? config.prefix + '_' : '';
	return prefix + key;
}

// 移除已添加的前缀
const autoRemovePrefix = (key) => {
	const len = config.prefix ? config.prefix.length + 1 : '';
	return key.substr(len)
	// const prefix = config.prefix ? config.prefix + '_' : '';
	// return  prefix + key;
}

/**
 * 加密方法
 * @param data
 * @returns {string}
 */
const encrypt = (data) => {
	if (typeof data === "object") {
		try {
			data = JSON.stringify(data);
		} catch (error) {
			console.log("encrypt error:", error);
		}
	}
	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();
}

/**
 * 解密方法
 * @param data
 * @returns {string}
 */
const decrypt = (data) => {
	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();
}


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/479382
推荐阅读
相关标签
  

闽ICP备14008679号