WebApp【公共组件库】@前端(For Git Submodule)
‘chensiAb’
2025-03-25 08c9d23e86b545a34e00a5fb5dae81ebabe50dea
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
 * 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();