封装 localStorage 缓存,兼容网页,微信小程序,uni-app
封装的缓存功能,兼容网页,微信小程序,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;
相关文章:

考csp所需算法_CSP vs RxJS:您所不知道的。
考csp所需算法by Kevin Ghadyani通过凯文加迪亚尼(Kevin Ghadyani) CSP vs RxJS:您所不知道的。 (CSP vs RxJS: what you don’t know.) CSP发生了什么? (What happened to CSP?) You probably clicked this article thinking “what is CSP?” It’s…

iOS蓝牙4.0开发例子
1建立中心角色 123#import <CoreBluetooth/CoreBluetooth.h> CBCentralManager *manager; manager [[CBCentralManager alloc] initWithDelegate:self queue:nil]; 2扫描外设(discover) [manager scanForPeripheralsWithServices:nil options:…
Spark Shuffle原理解析
Spark Shuffle原理解析 一:到底什么是Shuffle? Shuffle中文翻译为“洗牌”,需要Shuffle的关键性原因是某种具有共同特征的数据需要最终汇聚到一个计算节点上进行计算。 二:Shuffle可能面临的问题?运行Task的时候才会产…

云开发使用 got 的 get/post 传参请求示例代码
使用 got 进行网络请求的步骤: 1.创建云函数,并在终端执行云函数 2.执行 npm 安装 got ,命令:cnpm install --save got 3.在云函数中使用 示例代码: // 云函数入口文件 const cloud require(wx-server-sdk) cons…

JavaScript词法作用域的简单介绍
by Michael McMillan迈克尔麦克米兰(Michael McMillan) JavaScript词法作用域的简单介绍 (An easy intro to Lexical Scoping in JavaScript) Lexical scoping is a topic that frightens many programmers. One of the best explanations of lexical scoping can be found in…

Flex 布局详解 - 转自阮一峰老师
Flex 是 Flexible Box 的缩写,意为"弹性布局",用来为盒状模型提供最大的灵活性。任何的盒子都可以使用它。 下面我们来看一下使用 Flex 布局的容器的属性 flex-direction flex-wrap flex-flow justify-content align-items align-content 1.…

bzoj 1086: [SCOI2005]王室联邦
Description “余”人国的国王想重新编制他的国家。他想把他的国家划分成若干个省,每个省都由他们王室联邦的一个成员来管理。他的国家有n个城市,编号为1..n。一些城市之间有道路相连,任意两个不同的城市之间有且仅有一条直接或间接的道路。为…
在7分钟内深刻理解咖喱
Eric Elliott’s exceptional Composing Software series is initially what got me excited about functional programming. Its a must-read. 埃里克埃利奥特(Eric Elliott)杰出的合成软件系列最初使我对函数式编程感到兴奋。 这是必读的。 At one point in the series, he …

github后端开发面试题大集合(一)
作者:小海胆链接:https://www.nowcoder.com/discuss/3614?type0&order0&pos5&page0?fromwb来源:牛客网 转载自github,中文--->链接在这,英文---->链接在这文章较长,我把它拆分了三个部…

微信小程序左滑删除效果的实现完整源码附效果图
效果图: 功能描述,小程序列表左滑删除功能的实现完整源代码实现: <view wx:for{{friends}} wx:key"" wx:if{{groupType4}} catchtap"nav_oneChat" id"{{item._id}}" class"item p_r" style"…

Eclipse下修改工程名
一。 右键工程:Refactor->Rename,或选中工程按F2,修改名称 二。右键工程:Properties->Web Project Settings,修改Context Root三。1.找到项目所在位置(如图): 2.修改项目目录/.setting目录…

git操作手册_基本的Git手册
git操作手册介绍 (Introduction) Hi! I am Sanjula, and in this guide I hope to teach you a little bit about Git including:嗨! 我是Sanjula ,在本指南中,我希望教您一些有关Git的知识,包括: What Git is 什么是…

PHP 接入(第三方登录)QQ 登录 OAuth2.0 过程中遇到的坑
前言 绝大多数网站都集成了第三方登录,降低了注册门槛,增强了用户体验。最近看了看 QQ 互联上 QQ 登录的接口文档。接入 QQ 登录的一般流程是这样的:先申请开发者 -> 然后创建应用(拿到一组 AppId 和 AppKey)-> …

npm全局环境变量配置,全局配置cnpm
今天新电脑想安装node.js , 发现最新版本的node.js已经不支持win7了,但是又不想换系统,所以找了个旧版本,这里不多说了。如果找不到旧版本的node下载,可以去我的QQ交流群文件里面下载,QQ群号:17…

NTFS for Mac OS X:使用Brew安裝NTFS-3G
在最新的OSX系統中,其實已經完整兼容NTFS文件系統,只是出於安全考慮默認是以只讀模式掛載NTFS分區的,可以透過diskutil查詢硬碟UUID,重新以讀寫(rw)權限掛載,具體的可以參照這裡 當然,也有現成的軟體幫助你…

javascript开关_JavaScript开关案例简介
javascript开关In this short article, I will introduce you to JavaScript switch cases and how to use them with practical examples.在这篇简短的文章中,我将向您介绍JavaScript切换案例以及如何通过实际示例使用它们。 This article will explain better wi…

C++中一个class类对象占用多少内字节(7个例子,很清楚)
一个空的class在内存中多少字节?如果加入一个成员函数后是多大?这个成员函数存储在内存中什么部分? 一个Class对象需要占用多大的内存空间。最权威的结论是: *非静态成员变量总合。 *加上编译器为了CPU计算,作出的数据…

Java学习----到底调用哪一个方法(多态)
public class Father {public void print() {System.out.println("Father:print()");} } public class Son extends Father{// 方法的覆盖:子类重写父类的同名方法 Overridepublic void print() {System.out.println("Son:print()");}// Father…

mpvue 转uni-app 操作记录
1.创建一个uni-app 的项目,把原有的mpvue项目手动迁移过来 2.用到mpvue特性的代码,需要修改成uni-app 兼容的,例如 mpvue-wxparse 可以修改成 3.src/app.json 改成 pages.json ,路径格式需要改,如下格式 {"pages": [&…

桌面应用程序 azure_Azure Logic应用程序用例–黑色星期五
桌面应用程序 azureThis blog gives an overview of how Azure Serverless technologies came to rescue when the custom-built integration system went down. Also, it shows the high-level architecture solution built using Azure Serverless services like Logic Apps,…

PHP的静态变量介绍
静态变量只存在于函数作用域内,也就是说,静态变量只存活在栈中。一般的函数内变量在函数结束后会释放,比如局部变量,但是静态变量却不会。就是说,下次再调用这个函数的时候,该变量的值会保留下来。 只要在变…

MySQL 解压版创建用户密码
root 权限进入MySQL: mysql –uroot 查看当前MySQL用户: select user,host from mysql.user; 此处以User为root,Host为localhost的账户为例,将密码改为password的命令: SET PASSWORD FOR rootlocalhost PASSWORD(newp…

git 忽略指定文件夹的上传
我们在使用 git 开发的时候,有些插件的模块文件通过npm install 就可以下载,一般是不上传到 git 中的(因为文件太多会导致很耗时),例如 我的 node_modules 文件夹,不想上传,我们应该这么做。 我们需要创建一…

数据库初学者_面向初学者的免费6小时数据科学课程
数据库初学者Data science is considered the "sexiest job of the 21st century." Learn data science in this full 6-hour course for absolute beginners from Barton Poulson of datalab.cc.数据科学被认为是“ 21世纪最艰巨的工作”。 通过datalab.cc的 Barton…

网页抓取及下载
downAndroidApk.php <?php /* 命令行 d: cd ApacheServer\php php.exe D:\ApacheServer\web\crawl\downAndroidApk.php --appidFileD:\ApacheServer\web\crawl\youxi.txt --newDirD:\ApacheServer\web\crawl\requestNewDir*/ // 判断必须在php-cli模式下运行,即…

javascript中关于this指向问题详解
前 言 LiuDaP 在前端的学习中,我们必然要用到js,js可以说是前端必不可少的的东西。在学习js的过程中,我们会经常用到this这个东西,而this的指向问题就变得尤为重要。今天正好有空闲时间,就给大家详细介绍一下js中关于…

mpvue 转uniapp 导航栏样式错乱问题修复 tabbar 样式修复
效果图:修改前,修改后 找了半天没找到原因,只能自己改样式了,下面是样式代码(在app.vue 里面加上就行) <style>/*每个页面公共css */uni-tabbar {box-sizing: border-box;position: fixed;left: 0;bo…

css规则_CSS规则,将使您的生活更轻松
css规则by Nick Gard尼克加德(Nick Gard) CSS规则,将使您的生活更轻松 (CSS rules that will make your life easier) After years of writing and maintaining a couple of very large web projects and numerous smaller ones, I have developed some heuristics…

在mybatis中模糊查询有三种写法
<select id"selectStudentsByName" resultType"Student"> <!--第一种--> <!-- select id,name,age,score from student where name like % #{0} % --> <!--第二种--> <!-- select id,name,age,score from student wher…

BZOJ 3566: [SHOI2014]概率充电器
题目:http://www.lydsy.com/JudgeOnline/problem.php?id3566 首先这题正着想不好想,考虑补集转化。 先dfs一遍,令f[u](1-p[u])*∏(1-(1-f[v])*w) f[u]表示u这个点通过其子树并不能联通的概率。 然后考虑v从其父亲连过来的情况,设…