uni-app 中的 Storage 同浏览器的 localstorage
同步存储
setStorageSync
设置数据
try {uni.setStorageSync('storage_key', 'hello');} catch (e) {// error}
getStorageSync
获取数据
try {const value = uni.getStorageSync('storage_key');if (value) {console.log(value);}} catch (e) {// error}
removeStorageSync
删除数据
try {uni.removeStorageSync('storage_key');} catch (e) {// error}
clearStorageSync
清空数据
try {uni.clearStorageSync();} catch (e) {// error}
getStorageInfoSync
获取当前 storage 的相关信息
try {const res = uni.getStorageInfoSync();console.log(res.keys);console.log(res.currentSize);console.log(res.limitSize);} catch (e) {// error}
异步存储
setStorage
设置数据
uni.setStorage({key: 'storage_key',data: 'hello',success: function () {console.log('success');}});
getStorage
获取数据
uni.getStorage({key: 'storage_key',success: function (res) {console.log(res.data);}});
removeStorage
删除数据
uni.removeStorage({key: 'storage_key',success: function (res) {console.log('success');}});
clearStorage
清空数据
uni.clearStorage();
getStorageInfo
获取当前 storage 的相关信息
uni.getStorageInfo({success: function (res) {console.log(res.keys);console.log(res.currentSize);console.log(res.limitSize);}});
存储类的封装
由于正常使用的时候,并不需要用所有的 API,因此将最常用的几个 API 做了一层封装,需要用到其他 API 的时候再添加进去。
library/storage.js
class Storage {constructor () {}get (key) {return uni.getStorageSync(key);}set (key, value) {uni.setStorageSync(key, value);}remove (key) {uni.removeStorageSync(key);}clear () {uni.clearStorageSync();}}export default new Storage()
main.js
import storage from './library/storage'Vue.prototype.storage = storage
在组件中的使用:
this.storage.get('key');this.storage.set('key', 'value');this.storage.remove('key');this.storage.clear();
