Web-storage-apis

SunSeekerX ... 2021-6-3 大约 5 分钟

# Web-storage-apis

Github (opens new window)

online (opens new window)

简体中文 English

帮助你更好地使用浏览器的数据存储功能

  • 简单易懂的 api
  • 三种数据存储位置切换
  • 不支持Storage自动切换到Cookie进行数据存储
  • 数据可选可读与不可读
  • debug功能

# 使用 🔨

# 安装

# 使用npm
npm i web-storage-apis

# 或者 yarn

yarn add web-storage-apis
1
2
3
4
5
6
1
2
3
4
5
6

# 在 Vue 中使用

# 引入模块

app/src/main.js

import storage from 'web-storage-apis'
Vue.prototype.$storage = storage
1
2
1
2

# 测试代码

app/src/App.vue

<template>
  <div id="app">
    <h1>web-storage-apis test</h1>

    <div>
      <span class="primary">isReadable?:</span>
      <span
        class="value"
        :class="{
          success: storage && storage._config && storage._config.isReadable,
        }"
      >
        {{ storage && storage._config ? storage._config.isReadable : '-' }}
      </span>
    </div>

    <div>
      <span class="primary">debug?:</span>
      <span
        class="value"
        :class="{
          success: storage && storage._config && storage._config.debug,
        }"
      >
        {{ storage && storage._config ? storage._config.debug : '-' }}
      </span>
    </div>

    <div>
      <span class="primary">local storage?:</span>
      <span class="value" :class="{ success: local }">
        {{ local }}
      </span>
    </div>

    <div>
      <span class="primary">isUsingCookie?:</span>
      <span
        class="value"
        :class="{
          success: storage && storage._config && storage._config.isUsingCookie,
        }"
      >
        {{ storage && storage._config ? storage._config.isUsingCookie : '-' }}
      </span>
    </div>

    <div>
      <span class="primary">Support Storage?:</span>
      <span
        class="value"
        :class="{
          success: storage && storage._config && storage._config.isSupportStorage,
        }"
      >
        {{ storage && storage._config ? storage._config.isSupportStorage : '-' }}
      </span>
    </div>

    <div>
      <span class="primary">Support Cookie?:</span>
      <span
        class="value"
        :class="{
          success: storage && storage._config && storage._config.isSupportCookie,
        }"
      >
        {{ storage && storage._config ? storage._config.isSupportCookie : '-' }}
      </span>
    </div>

    <hr />

    <button
      class="bg-success"
      @click=";(storageSetting.isReadable = !storageSetting.isReadable), onChangeStorageConfig()"
    >
      切换可读配置
    </button>

    <button
      class="bg-success"
      @click=";(storageSetting.debug = !storageSetting.debug), onChangeStorageConfig()"
    >
      切换debug
    </button>

    <button class="bg-success" @click=";(local = !local), onChangeStorageConfig()">
      切换local
    </button>

    <button @click="onStorageData('DATA', 'Hello World!')"> Store String(Hello World!) </button>

    <button @click="onStorageData('DATA', true)"> Store Boolean(true) </button>

    <button @click="onStorageData('DATA', 1234567890)"> Store Number(1234567890) </button>

    <button @click="onStorageData('DATA', ['one', 'two', 'three'])">
      Store Array(['one', 'two', 'three'])
    </button>

    <button @click="onStorageData('DATA', { age: 11, name: '李白', emoji: '' })">
      Store Object({age: 11, name: '李白', emoji: '❤'})
    </button>

    <button class="bg-success" @click="onGetStorageData('DATA')"> 获取数据 </button>

    <button class="bg-warn" @click="onRemoveData('DATA')">移除数据</button>

    <button class="bg-warn" @click="onClearData()">清空数据</button>
  </div>
</template>

<script>
  import storage from './utils/bundle.esm'

  export default {
    name: 'App',
    data() {
      return {
        // 工具对象
        storage: null,
        // 是否存入localStorage
        local: false,
        storageSetting: {
          // 在localstorage无法使用的情况下是否使用cookie作为回退
          isUsingCookie: true,
          // 是否开启调试模式
          debug: false,
          // 写入的数据是否可读
          isReadable: true,
        },
      }
    },
    mounted() {
      // 初始化存储设置
      this.onChangeStorageConfig()
      this.storage = storage
    },
    methods: {
      // 改变storage设置
      onChangeStorageConfig() {
        storage.setConfig(this.storageSetting)
      },
      // 存入数据
      onStorageData(key, data) {
        storage.setStorageSync(key, data, this.local)
      },
      // 获取数据
      onGetStorageData(key) {
        console.log(storage.getStorageSync(key, this.local))
      },
      // 移除数据
      onRemoveData(key) {
        storage.removeStorageSync(key, this.local)
      },
      // 清空数据
      onClearData() {
        storage.clearStorageSync(this.local)
      },
    },
  }
</script>

<style>
  html,
  body {
    background-color: #f5f5f5;
  }
  #app {
    font-family: Avenir, Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin: 0 auto;
    max-width: 750px;
  }
  button {
    width: 100%;
    margin-bottom: 10px;
    color: #fff;
    background-color: #409eff;
    padding: 10px 0;
    border: none;
    outline: none;
    position: relative;
    overflow: hidden;
    border-radius: 10px;
  }
  button:after {
    content: '';
    display: block;
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    pointer-events: none;
    background-image: radial-gradient(circle, #666 10%, transparent 10.01%);
    background-repeat: no-repeat;
    background-position: 50%;
    transform: scale(10, 10);
    opacity: 0;
    transition: transform 0.3s, opacity 0.5s;
  }

  button:active:after {
    transform: scale(0, 0);
    opacity: 0.3;
    transition: 0s;
  }

  .bg-primary {
    background-color: #409eff;
  }
  .bg-success {
    background-color: #67c23a;
  }
  .bg-warn {
    background-color: #e6a23c;
  }

  .primary {
    font-weight: 700;
    font-size: 16px;
    color: #409eff;
  }
  .success {
    color: #67c23a;
  }
  .warn {
    color: #e6a23c;
  }
  .value {
    font-weight: 700;
    font-size: 16px;
  }
</style>
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239

# Apis 📄

# setConfig([options])

更改默认设置

参数 类型 默认 描述
options Object {} 设置对象
storage.setConfig({
    // 在localstorage无法使用的情况下是否使用cookie作为回退
    isUsingCookie: true,
    // 是否开启调试模式
    debug: false,
    // 写入的数据是否混淆
    isReadable: true,
})

// option 默认值
{
    // 在localstorage无法使用的情况下是否使用cookie作为回退
    isUsingCookie: true,
    // 是否开启调试模式
    debug: false,
    // 写入的数据是否可读
    isReadable: true,
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# setStorageSync(KEY,DATA[,LOCAL])

将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口。

参数 类型 默认 描述
key String 本地缓存中的指定的 key
data Any 需要存储的内容,只支持原生类型、及能够通过 JSON.stringify 序列化的对象
local Boolean false 是否使用 localStorage
try {
  setStorageSync('storage_key', 'hello', false)
} catch (error) {
  console.log(error.message)
}
1
2
3
4
5
1
2
3
4
5

# getStorageSync(KEY[,LOCAL])

从本地缓存中同步获取指定 key 对应的内容,这是一个同步接口

参数 类型 默认 描述
key String 本地缓存中的指定的 key
local Boolean false 是否使用 localStorage
try {
  const value = getStorageSync('storage_key', false)
  if (value) {
    console.log(value)
  }
} catch (error) {
  console.log(error.message)
}
1
2
3
4
5
6
7
8
1
2
3
4
5
6
7
8

# removeStorageSync(KEY[,LOCAL])

从本地缓存中同步移除指定 key。

参数 类型 默认 描述
key String 本地缓存中的指定的 key
local Boolean false 是否使用 localStorage
try {
  removeStorageSync('storage_key')
} catch (error) {
  console.log(error.message)
}
1
2
3
4
5
1
2
3
4
5

# clearStorageSync([LOCAL])

同步清理本地数据缓存。

参数 类型 默认 描述
local Boolean false 是否使用 localStorage
try {
  clearStorageSync()
} catch (error) {
  console.log(error.message)
}
1
2
3
4
5
1
2
3
4
5

# 为什么开发这个库 ❔

最近开发公司后台管理项目需要将数据持久化,利用 H5 的 localStorage 去保存但是原生的 api 接口非常不好用,因此对其进行了封装,api 风格借鉴了 uni-app 的数据接口风格 (opens new window)

  • 方便维护
  • 统一错误处理
  • 方便接入更多的项目

# 注意🔔

这个库正在我们公司的项目中使用,所以您可以放心地使用它。

如果您发现任何错误,请使用issue

谢谢。

# 数据混淆

如果开启了数据混淆,存入的数据会比原来的数据大,并且混淆过程需要计算时间。

如果未开启Cookie回退,在不支持使用Storage的情况下,数据无法写入,同时Cookie存储数据大小比Storage要小。

# 使用动图

example.gif

# 更新日志

  • 2020-04-23 1.3.3

    • 修复文档错误
    • 修复如果不支持Storage使用Cookie进行回滚操作存储数据永不过期的 bug
  • 2020-04-23 1.0.0

    • 重写逻辑
    • 加入 debug 功能
    • 加入存入到 cookie 功能
    • 加入手动配置信息功能
    • 加入存入数据混淆功能(默认关闭)
    • 加入如果Storage不可用,自动切换到Cookie功能(safari隐身模式下,Storage不可用)
  • 2020-02-21 0.0.2

    • 发布到 npm,可以使用 npm 安装了
    • 同时browser-storage-apis改名为web-storage-apis
  • 2019-09-16 0.0.1 添加版本信息

  • 2019-07-29 0.0.1 优化:获取不到指定 key 的值返回 null

  • 2019-07-27 0.0.1 第一次提交

上次编辑于: 2022年11月22日 00:59
贡献者: SunSeekerX