封装 localStorage 缓存,兼容网页,微信小程序,uni-app

585 阅读2分钟

封装的缓存功能,兼容网页,微信小程序,uni-app 使用,支持设置缓存,获取缓存,移除缓存,清空缓存,设置缓存时间,分组缓存设置。

 

把最下面的 Str4.js 代码拷贝到项目内可以直接使用,调用方式见下面的代码调用示例

 

封装的Js 文件在 uni-app 目录结构图:

uni-app 调用示例

<template>
	<view class="content">
		<view>{{testKey1}}</view>
		<view>{{testKey2}}</view>
		<view>{{testKey3}}</view>
	</view>
</template>

<script>
	import Str4 from '@/common/js/Str4.js';
	export default {
		data() {
			return {
				testKey1: 'AAA',
				testKey2: 'VVV',
				testKey3: '',
			}
		},
		mounted: function() {
			// 保存
			Str4.localStorage.set('testKey1','1111111111');
			Str4.localStorage.set('testKey2','222222222');
			Str4.localStorage.set('testKey3','333333333');
			//读取
			this.testKey1 = Str4.localStorage.get('testKey1');
			this.testKey2 = Str4.localStorage.get('testKey2');
			this.testKey3 = Str4.localStorage.get('testKey3');
		}
	}
</script>

<style>
	.content {}
</style>

h5调用示例

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<script type="text/javascript" src="./js/Str4.js"></script>
	</head>
	<body>
		<div id="testKey1"></div>
		<div id="testKey2"></div>
		<div id="testKey3"></div>

		<script> 
			// 1、保存
			Str.localStorage.set('testKey1', '我已经保存111111', 3600, 'group');
			Str.localStorage.set('testKey2', '我已经保存222222', 0, 'group');
			Str.localStorage.set('testKey3', '我已经保存333333', 0.01);

			// 2、读取
			var key1 = Str.localStorage.get('testKey1','group');
			document.getElementById('testKey1').innerText = key1;
			var key2 = Str.localStorage.get('testKey2','group');
			document.getElementById('testKey2').innerText = key2;
			var key3 = Str.localStorage.get('testKey3');
			document.getElementById('testKey3').innerText = key3;
			//Str.localStorage.remove('group');

			/* // 3、修改
			Str.localStorage.set('testKey2','我被修改了222');
			var key2 =  Str.localStorage.get('testKey2');
			document.getElementById('testKey2').innerText = key2;
			
			// 4、删除指定键
			Str.localStorage.remove('testKey3');
			var key3 =  Str.localStorage.get('testKey3');
			document.getElementById('testKey3').innerText = key3; */

			// 5、清空
			//Str.localStorage.clear();
		</script>
	</body>
</html>

Str4.js 代码封装:

var Str = {};
/*
 * 判断字符串是否为空
 */
Str.isNull = function(str) {
	if (str === undefined) return true;
	if (str === 'undefined') return true;
	if (str === null) return true;
	if (typeof str == 'string') str = str.replace(/^\s*|\s*$/g, "");
	if (str === '') return true;
	return false;
};
/*
 * 判断字符串是否为非空
 */
Str.isNotNull = function(str) {
	return !this.isNull(str);
};
/**
 * localStorage操作
 */
Str.localStorage = {
	/**
	 * 保存
	 * @param {Object} key 键名
	 * @param {Object} value 键值
	 * @param int second 缓存时间(单位:秒)
	 * @param string ctag 组名
	 */
	set: function(key, value, second = null, ctag = null) {
		if (Str.isNull(second) || second == 0) second = 86400 * 365 * 10;
		var data = {
			value: value,
			expire: parseInt((new Date()).getTime() / 1000) + second
		};
		if (Str.isNotNull(ctag)) {
			// 如果存在组主键名,则保存在组主键下
			let baseVal = this.get(ctag) || {};
			baseVal[key] = data;
			data = {
				value: baseVal,
				expire: parseInt(new Date().getTime() / 1000) + 86400 * 365 * 10
			};
			key = ctag;
		}
		if (localStorage != undefined) {
			localStorage.setItem(key, JSON.stringify(data));
		} else if (uni.setStorageSync != undefined) {
			uni.setStorageSync(key, JSON.stringify(data));
		} else if (wx.setStorageSync != undefined) {
			wx.setStorageSync(key, JSON.stringify(data));
		}
	},
	/**
	 * 读取
	 * @param {Object} key 键名
	 */
	get: function(key, ctag) {
		let _key = key;
		if (Str.isNotNull(ctag)) {
			key = ctag; // 如果存在组主键名,则读取组主键内容
		}
		var data = null;
		if (localStorage != undefined) {
			data = localStorage.getItem(key);
		} else if (uni.getStorageSync != undefined) {
			data = uni.getStorageSync(key);
		} else if (wx.getStorageSync != undefined) {
			data = wx.getStorageSync(key);
		}
		if (Str.isNotNull(data)) {
			if (typeof data == 'string') data = JSON.parse(data);
			if (Str.isNotNull(ctag)) {
				if (data.expire != null && data.expire * 1000 < new Date().getTime()) {
					this.remove(ctag);
					return null;
				}
				data = data.value[_key]; // 重新赋值
				if (Str.isNull(data)) return null;
			}
			if (data.expire != null && data.expire * 1000 < new Date().getTime()) {
				this.remove(_key, ctag);
				return null;
			}
			return data.value;
		}
		return null;
	},
	/**
	 * 删除指定键
	 * @param key       键名
	 * @param ctag      组主键名
	 */
	remove: function(key, ctag) {
		if (Str.isNotNull(ctag)) {
			if (Str.isNull(key)) {
				key = ctag;
			} else {
				let baseVal = this.get(ctag) || {};
				delete baseVal[key];
				if (JSON.stringify(baseVal) == '{}') key = ctag;
				else this.set(ctag, baseVal, null);
			}
		}
		if (localStorage != undefined) {
			localStorage.removeItem(key);
		} else if (uni.removeStorageSync != undefined) {
			uni.removeStorageSync(key);
		} else if (wx.removeStorageSync != undefined) {
			wx.removeStorageSync(key);
		}
	},
	/**
	 * 清空
	 */
	clear: function() {
		if (localStorage != undefined) {
			localStorage.clear();
		} else if (uni.clearStorageSync != undefined) {
			uni.clearStorageSync();
		} else if (wx.clearStorageSync != undefined) {
			wx.clearStorageSync();
		}
	}
};

if (typeof module != 'undefined') module.exports = Str;