/**
|
* LocalStorage - 混合App模式,本地存储同步工具
|
* @tutorial 注意:混合App模式中,不建议使用 Taro.setStorageSync 存储数据
|
* 因为Taro API无法区分不同开发环境,测试环境与正式环境存储的本地数据,读取时会串通
|
* 本方法解决方式在于,给键名增加了开发环境的前缀,例如:AiSim.lc@***、AiSim.wc@***、AiSim.rb@***
|
* @author Tevin
|
*/
|
|
import Taro from '@tarojs/taro';
|
|
export class LocalStorage {
|
constructor() {
|
this._data = {
|
prefixType: process.env.TARO_ENV === 'h5' ? 'h5' : 'wx',
|
};
|
}
|
|
// 初始化
|
initial(prefixType) {
|
this._data.prefixType = prefixType;
|
}
|
|
load(key, defaultType = 'obj') {
|
const name = 'AiSim.' + this._data.prefixType + '@' + key;
|
const data = Taro.getStorageSync(name);
|
if (data) {
|
return JSON.parse(data);
|
} else {
|
if (defaultType === 'obj') {
|
return {};
|
} else if (defaultType === 'arr') {
|
return [];
|
}
|
}
|
}
|
|
loadArr(key) {
|
return this.load(key, 'arr');
|
}
|
|
save(key, value) {
|
if (typeof value !== 'object') {
|
throw new Error('LocalStorage save 方法,value 只接收 Object !');
|
}
|
const name = 'AiSim.' + this._data.prefixType + '@' + key;
|
Taro.setStorageSync(name, JSON.stringify(value || {}));
|
}
|
|
remove(key) {
|
const name = 'AiSim.' + this._data.prefixType + '@' + key;
|
Taro.removeStorageSync(name);
|
}
|
|
getKeys() {
|
const info = Taro.getStorageInfoSync();
|
const keys = [];
|
const prefix = 'AiSim.' + this._data.prefixType + '@';
|
info.keys.forEach(storageKey => {
|
if (storageKey.indexOf(prefix) === 0) {
|
const keyName = storageKey.split('@')[1];
|
keys.push(keyName);
|
}
|
});
|
return keys;
|
}
|
|
searchKey(key) {
|
const matches = [];
|
this.getKeys().forEach(keyName => {
|
if (keyName.indexOf(key) >= 0) {
|
matches.push(keyName);
|
}
|
});
|
return matches;
|
}
|
|
// 清除本地存储工具保存的所有数据
|
cleanAll() {
|
const info = Taro.getStorageInfoSync();
|
const prefixReg = /^AiSim\.[a-zA-Z]+@/;
|
info.keys.forEach(storageKey => {
|
if (prefixReg.test(storageKey)) {
|
Taro.removeStorageSync(storageKey);
|
}
|
});
|
}
|
|
}
|
|
export const $localStorage = new LocalStorage();
|