From 1521ce6c4334f30dbfba0ec0228cd236681f61cb Mon Sep 17 00:00:00 2001
From: Tevin <tingquanren@163.com>
Date: Wed, 24 Nov 2021 10:12:53 +0800
Subject: [PATCH] 本地存储改进版,转移到公共模块

---
 common/LocalStorage.js |   64 ++++++++++++++++++++++++++++++++
 1 files changed, 64 insertions(+), 0 deletions(-)

diff --git a/common/LocalStorage.js b/common/LocalStorage.js
new file mode 100644
index 0000000..b1eb5a0
--- /dev/null
+++ b/common/LocalStorage.js
@@ -0,0 +1,64 @@
+/**
+ * LocalStorage - 混合App模式,本地存储同步工具
+ *  用于区分不同开发环境读取不同数据
+ * @author Tevin
+ */
+
+import Taro from '@tarojs/taro';
+
+export class LocalStorage {
+    constructor() {
+        this._data = {
+            prefixType: '',
+        };
+    }
+
+    // 初始化
+    initial(prefixType) {
+        this._data.prefixType = prefixType;
+    }
+
+    load(key) {
+        const name = 'AiSim.' + this._data.prefixType + '@' + key;
+        return JSON.parse(Taro.getStorageSync(name) || '{}');
+    }
+
+    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;
+    }
+
+}
+
+export const $localStorage = new LocalStorage();
\ No newline at end of file

--
Gitblit v1.9.1