uni-app的uni.setStorageSync和uni.setStorage缓存数据

[复制链接]
发表于 2023-1-13 15:23:00 | 显示全部楼层 |阅读模式
setStorageSync
同步存储 
uni.setStorageSync("username","lty")

  同步读取 

let res=uni.getStorageSync("username")
this.username=res

 

setStorage

//异步存储

uni.setStorage({
    key:'id',
    data:80,
    success() {
         console.log('存储成功!')
        }
})

//异步读取

uni.getStorage({
    key:'id',
    success(res){
    console.log(res)
    this.username=res.data
    console.log(this.username)
}

uni-app同步缓存值 设置 读取 删除

//存储一个字符传值
uni.setStorageSync('storage_key', 'hello');

//存储数组前,将数组转为字符串
uni.setStorageSync('mykeymas',JSON.stringify(this.msg))
//同步获取字符串
const value = uni.getStorageSync('storage_key');
console.log('获取的key',value)
    
//将字符串转为对象        
let  con= JSON.parse(uni.getStorageSync('mykeymas'));
console.log('获取的mykeymas',con)
uni.setStorageSync('storage_key', 'hello');  //设置
uni.getStorageSync('storage_key');            //读取
const res = uni.getStorageInfoSync();        //读取所有的值

uni.removeStorageSync('storage_key');        //清除某一个特定的key
uni.clearStorageSync();                      //清除所有的key

 



来源:https://www.cnblogs.com/hailexuexi/p/17049788.html
回复

使用道具 举报

发表于 2026-10-10 17:40:27 | 显示全部楼层
感谢楼主的分享!

很实用的uni-app存储教程,讲解得很清楚!同步和异步两种方式都包含进去了,对于新手来说很有帮助。

补充几点小建议:
  1. // 异步存储还可以这样写,更简洁
  2. uni.setStorage({
  3.     key: 'id',
  4.     data: 80
  5. }).then(() => {
  6.     console.log('存储成功')
  7. })
  8. //异步读取也可以用 Promise 方式
  9. const res = await uni.getStorage({ key: 'id' })
  10. console.log(res.data)
复制代码

另外如果是存储对象或数组,记得一定要用JSON.stringify()转成字符串,取出来的时候再用JSON.parse()转回来,这个楼主已经提到了,很棒!

还有一个小技巧:如果担心同步操作会阻塞主线程,在大规模数据处理时建议还是用异步的setStorage/getStorage。

有问题欢迎随时交流,共同进步!

来源:https://ym.gs/forum.php
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

圆梦公社,专注于为全球华人提供纯粹技术交流的地方,请勿发布任何政治及违法的言论。如有相关侵权、举报、投诉及建议等,请发 E-mail:dzh188@hotmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部