一.同步操作本地存储除非必要时候,尽量使用同步方法,特别是新手,建议使用同步方法,除非同步方法解决不了问题考虑使用异步方法。【相关学习推荐:小程序开发教程】
wx.setstoragesync同步存:wx.setstoragesync('key', 'value')
效果可以在微信小程序调试器中看如下
wx.getstoragesync同步获取:wx.getstoragesync('key')console.log(wx.getstoragesync('key'))//value
wx.getstorageinfosync()当前 storage 中的信息const res = wx.getstorageinfosync()console.log(res.keys)//["logs", "key"]//res.keys当前 storage 中所有的 keyconsole.log(res.currentsize)//1//res.currentsize当前占用的空间大小, 单位 kbconsole.log(res.limitsize)//10240//res.limitsize限制的空间大小,单位 kb
wx.removestoragesync同步移除某一个:wx.removestoragesync('key')
移除之后叫做key的storage就会消失不见
wx.clearstoragesync同步清除所有:wx.clearstoragesync()
如下使用clearstoragesync连同之前的logs都会清除掉
二.异步操作本地存储1.wx.setstorage异步存储值;将数据存储在本地缓存中指定的 key 中。会覆盖掉原来该 key 对应的内容。除非用户主动删除或因存储空间原因被系统清理,否则数据都一直可用。单个 key 允许存储的最大数据长度为 1mb,所有数据存储上限为 10mb。
wx.setstorage({ key:"key2", data:"value2"})
当我们存储了值之后就可以在微信小程序的调试栏器中看到效果了,同步跟异步除了存取执行的操作不一样之外,结果是一样的,都是存,拿值,结果是一样的,只是同步是顺序执行,而异步则是不会让界面停滞,但是这种几乎可以忽略不记,所以建议大家没有必要的话就使用同步了。
2.wx.removestorage()移除指定的值从本地缓存中移除指定 key。
wx.removestorage({ key: 'key', success (res) { console.log(res) }})
3.wx.getstorage(); 获取值从本地缓存中异步获取指定 key 的内容。
wx.getstorage({ key: 'key', success (res) { console.log(res.data) }})
4.wx.getstorageinfo获取当前 storage 中的信息wx.getstorageinfo({ success (res) { console.log(res.keys)//["logs", "key"] //当前 storage 中所有的 key console.log(res.currentsize)//1 //当前占用的空间大小, 单位 kb console.log(res.limitsize)//10240 //限制的空间大小,单位 kb}})
5.wx.clearstorage(); 清除所有的keywx.clearstorage()
更多编程相关知识,请访问:编程入门!!
以上就是聊聊小程序中怎么同步或异步操作本地存储的详细内容。