#author("2022-12-16T09:44:29+08:00","default:Admin","Admin")
#author("2022-12-16T09:46:23+08:00","default:Admin","Admin")
[[uni-app]]

&color(red){※前提条件:vue3 的uniapp开发};

#contents

*概要 [#tfb8e5af]

- uni.setStorage(OBJECT) 在客户端存储键值对数据(异步的)
- uni.setStrorageSysnc(KEY,DATA) 在客户端存储键值对数据(同步的)
- uni.getStorage(OBJECT) 读取保存在客户端的键值对数据(异步的)
- uni.getStrorageSysnc(KEY) 读取保存在客户端的键值对数据(同步的)
- uni.removeStorage(OBJECT) 从本地缓存中异步移除指定 key。
- uni.removeStorageSync(KEY)从本地缓存中同步移除指定 key。

uni-app的Storage在不同端的实现不同:

- H5端为localStorage,浏览器限制5M大小,是缓存概念,可能会被清理
- App端为原生的plus.storage,无大小限制,不是缓存,是持久化的
- 各个小程序端为其自带的storage api,数据存储生命周期跟小程序本身一致,即除用户主动删除或超过一定时间被自动清理,否则数据都一直可用。

官方文档:

 https://uniapp.dcloud.net.cn/api/storage/storage.html
** uni.setStorage的写法 [#xd567a3f]
#codeprettify{{
uni.setStorage({
		key: 'storage_key',
		data: {},
		success: () => {}
});
}}

跳转之前先清除一下之前数据,再存储一下本次数据。

#codeprettify{{
uni.removeStorage({
    key: 'hello'
})
uni.setStorage({
    key: 'hello',
    data: 'helloSetStorage',
    //data: JSON.stringify(item)//如果存储得数据是对象,记得转一下
})
}}
** uni.setStorageSync的写法 [#w1f94a86]

#codeprettify{{
try {
		uni.setStorageSync(
			'storage_key',
			{},
		)
	} catch (e) {
	    // error
}
}}

* 使用方法 [#xcc26259]

** 保存 [#idec0766]

#codeprettify{{
let items = JSON.stringify(数组或者对象);
uni.setStorageSync("wqzdy" , items);
}}

取出

#codeprettify{{
var data = uni.getStorageSync("wqzdy" );
var items = JSON.parse(data)
}}

** uni.navigateTo传递数组对象 [#zbb37609]

#codeprettify{{
let items = JSON.stringify(item)
uni.navigateTo({
    url: '../order/refundMoney/refundMoney?item=' + items
})
}}


取出
#codeprettify{{
onLoad(e) { 
    this.item = JSON.parse(e.item)  
},
}}

* Troubleshooting [#g2d949bd]

** Uncaught Error: getStorageSync:fail parameter `key`. Expected String with value "undefined", got Undefined [#z0498bec]


原因是setStorageSync这个同步接口参数不是接收一个key,value形式的对象,而是两个参数,分别是key,value。



#hr();
Comment:
#comment_kcaptcha

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS