微信小程式封裝快取過期時間
阿新 • • 發佈:2020-08-04
utils
新建storage.js檔案
- var dtime = '_deadtime';
- function put(k, v, t) {
- wx.setStorageSync(k, v)
- var seconds = parseInt(t);
- if (seconds > 0) {
- var timestamp = Date.parse(new Date());
- timestamp = timestamp / 1000 + seconds;
-
wx.setStorageSync(k + dtime, timestamp + "")
- } else {
- wx.removeStorageSync(k + dtime)
- }
- }
- function get(k, def) {
- var deadtime = parseInt(wx.getStorageSync(k + dtime))
- if (deadtime) {
- if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {
- if (def) { return def; } else { return; }
- }
- }
- var res = wx.getStorageSync(k);
- if (res) {
- return res;
- } else {
- return def;
- }
- }
- function remove(k) {
- wx.removeStorageSync(k);
- wx.removeStorageSync(k + dtime);
- }
- function clear() {
- wx.clearStorageSync();
- }
-
module.exports = {
- put: put,
- get: get,
- remove: remove,
- clear: clear,
- }
js引用
let util = require('../../utils/storage.js');
使用方法:
- 設定快取:util.put('key','value',604800) 表示設定快取失效時間為一週;
- 獲取快取:util.get('key')
- 清除快取:util.remove('key')
- 清除所有快取:util.clear() https://blog.csdn.net/weixin_44694538/article/details/103728983