微信小程序-Storage
官方文档地址:https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.setStorageSync.html
?> Storage 本地存储,和原生前端开发差不多,单个 Key 允许存储的最大数据长度为 1MB, 所有数据存储上限为 10MB。
存储数据
?> 带了 Sync 就是同步的方法,没有带就是异步的
setStorageSync/setStorage
将数据存储在本地缓存中指定的 key 中。会覆盖掉原来该 key 对应的内容。除非用户主动删除或因存储空间原因被系统清理,否则数据都一直可用。单个 key 允许存储的最大数据长度为 1MB,所有数据存储上限为 10MB。
<!--index.wxml-->
<text>首页</text>
<button bindtap="onStorage">测试 Storage Api</button>
// index.js
Page({
onStorage() {
wx.setStorageSync('name', 'BNTang')
wx.setStorage({
key: 'age',
data: 'BNTang',
encrypt: true,
success() {
wx.getStorage({
key: 'age',
encrypt: true,
success(res) {
console.log(res.data)
}
})
}
})
}
})
!> encrypt: true 本博主使用的微信开发版本是 2.32.0 存储数据进行加密没有效果,如有人知道为啥还请麻烦引导下
?> 2023年6月6日14:53:55,今日,我换了台电脑打开了微信开发者工具测试了如上的 encrypt: true 成功加密了,解决了问题(目前还不知道什么原因造成的)
getStorageSync/getStorage
<!--index.wxml-->
...
<button bindtap="onGetStorage">测试 Storage Api Get</button>
// index.js
Page({
...
onGetStorage() {
let name = wx.getStorageSync('name')
console.log(name);
wx.getStorage({
key: 'name',
success (res) {
console.log(res.data)
}
})
}
})
clearStorage/clearStorageSync
<!--index.wxml-->
...
<button bindtap="onClearStorage">测试 Storage Api Clear</button>
// index.js
Page({
...
onClearStorage() {
wx.clearStorageSync()
wx.clearStorage()
}
})
removeStorage/removeStorageSync
<!--index.wxml-->
...
<button bindtap="onRmoveStorage">测试 Storage Api Rmove</button>
// index.js
Page({
...
onRmoveStorage() {
wx.removeStorage({
key: 'name',
success (res) {
console.log(res)
}
});
wx.removeStorageSync('name')
}
})
!> 注意点:同步和异步可以交叉使用,也就是说,同步存的可以异步取等等
应用场景
- 存完之后立刻需要取,就用同步方法
- 存完之后不需要立刻取,就用异步方法

浙公网安备 33010602011771号