ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
* [cache.js](https://www.kancloud.cn/wangking/uniapp/1897988#cachejs_1) * [main.js 中注册该方法](https://www.kancloud.cn/wangking/uniapp/1897988#mainjs__91) * [客户端调用](https://www.kancloud.cn/wangking/uniapp/1897988#_111) ## cache.js > 存放路径 /common/cache.js ~~~ /** * 缓存数据优化 * var cache = require('utils/cache.js'); * import cache from '../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} */ var postfix = '_xjsU'; // 缓存前缀 /** * 设置缓存 * @param {[type]} k [键名] * @param {[type]} v [键值] * @param {[type]} t [时间、单位秒] */ function set(k, v, t) { uni.setStorageSync(k, v) var seconds = parseInt(t); if (seconds > 0) { var timestamp = Date.parse(new Date()); timestamp = timestamp / 1000 + seconds; uni.setStorageSync(k + postfix, timestamp + "") } else { uni.removeStorageSync(k + postfix) } } /** * 获取缓存 * @param {[type]} k [键名] * @param {[type]} def [获取为空时默认] */ function get(k, def) { var deadtime = parseInt(uni.getStorageSync(k + postfix)) if (deadtime) { if (parseInt(deadtime) < Date.parse(new Date()) / 1000) { if (def) { return def; } else { return false; } } } var 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); } /** * 清理所有缓存 * @return {[type]} [description] */ function clear() { uni.clearStorageSync(); } module.exports = { set: set, get: get, remove: remove, clear: clear } ~~~ ## main.js 中注册该方法 > 路径 /main.js ~~~ import Vue from 'vue' import App from './App' import cache from './common/cache.js' Vue.config.productionTip = false Vue.prototype.$cache = cache App.mpType = 'app' const app = new Vue({ ...App }) app.$mount() ~~~ ## 客户端调用 ~~~ <template> <view> <button type="default" @tap="setCache">设置缓存</button> <button type="default" @tap="getCache">获取缓存</button> <button type="default" @tap="clearCache">删除缓存</button> </view> </template> <script> export default { methods: { setCache: function(e) { this.$cache.set('name', 'haha123'); }, getCache: function(e) { let name = this.$cache.get('name'); console.log("name is : " + name) }, clearCache: function(e) { this.$cache.clear(); }, } } </script> ~~~