在uni-app中使用:
/**
* 缓存数据优化
* import cache from '@/common/js/cache'
* 使用方法 【
* 一、设置缓存
* string cache.put('k', 'string你好啊');
* json cache.put('k', { "b": "3" }, 2);
* array cache.put('k', [1, 2, 3]);
* boolean cache.put('k', true);
* 二、读取缓存
* 默认值 cache.get('k')
* string cache.get('k', '你好')
* json cache.get('k', { "a": "1" })
* 三、移除/清理
* 移除: cache.remove('k');
* 清理:cache.clear();
* 】
* @type {String}
*/
const postfix = '_msfkd'; // 缓存前缀
const expires = 1000*60*30;//设置缓存时间 ms
/**
* 设置缓存
* @param {[type]} k [键名]
* @param {[type]} v [键值]
* @param {[type]} t [时间、单位秒]
*/
function put(k, v, t) {
uni.setStorageSync(k, v)
let seconds =t;
if (seconds > 0) {
let timestamp = new Date().getTime();
if(k=="userInfo"){
uni.setStorageSync(k + postfix, seconds*expires + "")
}else{
let newTime = seconds*18000000+timestamp;//缓存时间
uni.setStorageSync(k + postfix, newTime + "")
}
} else {
uni.removeStorageSync(k + postfix)
}
}
/**
* 获取缓存
* @param {[type]} k [键名]
* @param {[type]} def [获取为空时默认]
*/
function get(k, def) {
let deadtime = parseInt(uni.getStorageSync(k + postfix))
if (deadtime) {
let date = new Date().getTime();
if ( date - deadtime >expires ) {//清空缓存
remove(k)
remove(k+postfix)
}else{
return uni.getStorageSync(k)
}
}else{
let res = uni.getStorageSync(k);
if (res) {
return res;
} else {
if (def == undefined || def == "") {
def = false;
}
return def;
}
}
}
function remove(k) {
uni.removeStorageSync(k);
uni.removeStorageSync(k + postfix);
}
export default {
put,
get,
remove,
}
支付宝原生小程序内:
// 优化缓存
// * 使用方法 【
// * 一、设置缓存
// * string cache.put('k', 'string你好啊');
// * json cache.put('k', { "b": "3" }, 2);
// * array cache.put('k', [1, 2, 3]);
// * boolean cache.put('k', true);
// * 二、读取缓存(可设置默认值),没有读取到缓存值,使用设置的默认值
// * 默认值 cache.get('k')
// * string cache.get('k', '你好')
// * json cache.get('k', { "a": "1" })
// * 三、移除/清理
// * 移除: cache.remove('k');
// * 清理:cache.clear();
// * 】
const postfix = "_msfkd";//缓存前缀
const expiress = 1000* 60*60;//设置缓存时间ms 默认一个小时
/**
*设置缓存
@param {[type]} k [键名]
@param {[type]} v [键值]
@param {[type]} t [时间、单位ms]
*/
function put(k,v,t){
my.setStorageSync({
key: k,
data: v
});
let seconds = t;
if(seconds>0){//如果存在t 设置缓存时间
my.setStorageSync({
key: k+postfix,
data: seconds*expiress
});
}else{//移除时间缓存
my.removeStorageSync({
key: k+postfix
});
}
}
/**
* 获取缓存 (可添加默认值)
* @param {[type]} k [键名]
* * @param {[type]} def [获取为空时默认]
*/
function get(k,def){
let deadtime = my.getStorageSync({
key: k+postfix
}).data;
deadtime = parseInt(deadtime);
if(deadtime){
let date = new Date().getTime();
if(date-deadtime>expiress){
remove(k)
}else{
return my.getStorageSync({
key:k
}).data;
}
}else{
let res = my.getStorageSync({
key:k
}).data;
if(res) return res;
if (def == undefined || def == "") {
def = false;
}
return def;
}
}
/**
* 移除缓存
* @param {*} k
*/
function remove(k) {
my.removeStorageSync(k);
my.removeStorageSync(k + postfix);
}
/**
* 删除全部缓存
*/
function clear(){
my.clearStorageSync();
}
export default {
put,
get,
remove,
clear
}