95 lines
2.8 KiB
JavaScript
95 lines
2.8 KiB
JavaScript
import constant from './constant'
|
||
|
||
// 存储变量名前缀
|
||
let storageKey = constant.storageKey;
|
||
|
||
const storage = {
|
||
init: function(key) {
|
||
if (key === storageKey) {
|
||
return false;
|
||
}
|
||
if (typeof key === 'string') {
|
||
return key;
|
||
} else if (typeof key === 'object') {
|
||
return key['prefix'];
|
||
}
|
||
},
|
||
set: function(key, value, params = null) {
|
||
var _key = this.init(key);
|
||
// console.log('比较两个KEY', key, _key)
|
||
if (!_key) {
|
||
return;
|
||
}
|
||
let tmp = uni.getStorageSync(storageKey)
|
||
tmp = tmp ? tmp : {}
|
||
if (_key === key) {
|
||
tmp[key] = value;
|
||
} else {
|
||
tmp[_key] = tmp[_key] || {};
|
||
if (params === null || params === 'undefined') {
|
||
//不加params参数,则将该项原有数据全部抹除后写入新value作为对象唯一的一个值
|
||
//只有在明确设置了为null 或者 undifined才是
|
||
//注意:已知问题:参数(object的键名)不允许是负数
|
||
tmp[_key] = {
|
||
0: value
|
||
};
|
||
} else {
|
||
//添加参数,则为指定覆盖方式,对其他项不产生影响
|
||
tmp[_key][params] = value;
|
||
}
|
||
}
|
||
|
||
uni.setStorageSync(storageKey, tmp)
|
||
},
|
||
get: function(key, params = null) {
|
||
var _key = this.init(key);
|
||
if (!_key) {
|
||
return false;
|
||
}
|
||
let tmp = uni.getStorageSync(storageKey)
|
||
tmp = tmp ? tmp : {}
|
||
if (_key === key) {
|
||
return tmp[key] || "";
|
||
} else {
|
||
return (tmp[_key] ? (tmp[_key][params] || "") : "");
|
||
}
|
||
},
|
||
all: function(key) {
|
||
//获取指定键的全部缓存
|
||
var _key = this.init(key);
|
||
if (!_key) {
|
||
return false;
|
||
}
|
||
let tmp = uni.getStorageSync(storageKey)
|
||
tmp = tmp ? tmp : {}
|
||
if (_key === key) {
|
||
return tmp[key] || "";
|
||
} else {
|
||
return tmp[_key] || [];
|
||
}
|
||
},
|
||
remove: function(key, params = null) {
|
||
var _key = this.init(key);
|
||
if (!_key) {
|
||
return;
|
||
}
|
||
let tmp = uni.getStorageSync(storageKey)
|
||
tmp = tmp ? tmp : {}
|
||
if (_key === key) {
|
||
delete tmp[key];
|
||
} else {
|
||
delete tmp[_key][params];
|
||
}
|
||
uni.setStorageSync(storageKey, tmp)
|
||
},
|
||
clean: function() {
|
||
uni.removeStorageSync(storageKey)
|
||
},
|
||
info: function() {
|
||
//返回当前缓存情况 https://uniapp.dcloud.net.cn/api/storage/storage.html#getstorageinfo
|
||
//currentSize 当前占用空间 kb; keys,所有缓存键key
|
||
return uni.getStorageInfoSync(); //只能获取全部,无法指定key
|
||
}
|
||
}
|
||
|
||
export default storage |