var dtime = '_deadtime';
/**
* 设置本地缓存
* k key
* v value
* t time
*/
function setStorage(k, v, t) {
wx.setStorageSync(k, v);
let seconds = parseInt(t);
if (seconds > 0) {
let timestamp = Date.parse(new Date());
timestamp = timestamp / 1000 + seconds;
wx.setStorageSync(k + dtime, timestamp + "");
} else {
wx.removeStorageSync(k + dtime);
}
}
/**
* 根据名称获取数据缓存
* k key
*/
function getStorage(k, def) {
let deadtime = parseInt(wx.getStorageSync(k + dtime));
if (deadtime) {
if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {
if (def) {
return def;
} else {
return;
}
}
}
let res = wx.getStorageSync(k);
if (res) {
return res;
} else {
return def;
}
}
/**
* 根据名称删除指定本地缓存
* k key
*/
function removeStorage(k) {
wx.removeStorageSync(k);
wx.removeStorageSync(k + dtime);
}
/**
* 清空全部本地缓存
*/
function clearStorage() {
wx.clearStorageSync();
}
// 模板语言转换
module.exports = {
setStorage: setStorage,
getStorage: getStorage,
removeStorage: removeStorage,
clearStorage: clearStorage
}
调用方式:
let testVal = '123456';
common.setStorage('test', testVal, 604800); // 设置缓存,缓存时间S
common.getStorage('test'); // 取缓存
common.removeStorage('test'); // 删除指定缓存
common.clearStorage(); // 删除全部