wlzboy
7 小时以前 5f2ee03958a1a16dc27195c76ea7cffb422c95d1
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
import constant from './constant'
 
// 存储变量名
let storageKey = 'storage_data'
 
// 存储节点变量名
let storageNodeKeys = [constant.avatar, constant.name, constant.roles, constant.permissions]
 
const storage = {
  set: function(key, value) {
    if (storageNodeKeys.indexOf(key) != -1) {
      let tmp = uni.getStorageSync(storageKey)
      tmp = tmp ? tmp : {}
      tmp[key] = value
      uni.setStorageSync(storageKey, tmp)
    }
  },
  get: function(key) {
    let storageData = uni.getStorageSync(storageKey) || {}
    return storageData[key] || ""
  },
  remove: function(key) {
    let storageData = uni.getStorageSync(storageKey) || {}
    delete storageData[key]
    uni.setStorageSync(storageKey, storageData)
  },
  clean: function() {
    uni.removeStorageSync(storageKey)
  },
  // 新增:获取存储信息
  getStorageInfo: function() {
    try {
      const info = uni.getStorageInfoSync()
      console.log('💾 存储信息:', {
        keys: info.keys,
        currentSize: info.currentSize,
        limitSize: info.limitSize,
        usage: ((info.currentSize / info.limitSize) * 100).toFixed(2) + '%'
      })
      return info
    } catch (e) {
      console.error('获取存储信息失败:', e)
      return null
    }
  },
  // 新增:清理所有存储(慎用)
  clearAll: function() {
    try {
      uni.clearStorageSync()
      console.log('✅ 清理所有存储成功')
    } catch (e) {
      console.error('清理存储失败:', e)
    }
  },
  // 新增:检查并清理过期数据
  checkAndClean: function() {
    try {
      const info = uni.getStorageInfoSync()
      const usagePercent = (info.currentSize / info.limitSize) * 100
      
      // 如果使用超过 80%,提示用户
      if (usagePercent > 80) {
        console.warn('⚠️ 存储空间使用超过 80%:', usagePercent.toFixed(2) + '%')
        
        // 自动清理非必要的缓存
        const keysToKeep = [storageKey, 'token', 'uni-id-pages-userInfo']
        info.keys.forEach(key => {
          if (!keysToKeep.includes(key)) {
            try {
              uni.removeStorageSync(key)
              console.log('🗑️ 清理缓存:', key)
            } catch (e) {
              console.error('清理失败:', key, e)
            }
          }
        })
      }
    } catch (e) {
      console.error('检查存储失败:', e)
    }
  }
}
 
export default storage