4.4.1wx.setStorage和wx.setStorageSync
wx.setStorage异步版本,wx.setStorageSync同步版本。两者都是将数据存储在本地缓存中指定的key中
wx.setStorage({key:"key",data:"value"})
wx.setStorageSync("key","value")
data是需要存储的内容,只支持原生类型、Date,以及能够通过JSON.stringify序列化的对象。
4.4.2wx.removeStorage和wx.removeStorageSync
wx.removeStorage是异步版本,wx.removeStorageSync是同步版本。两者都是将数据从本地缓存中移除。
wx.removeStorage({key:"key",success(res){
console.log(res)}})
wx.removeStorageSync("key")
4.4.3wx.getStorage和wx.getStorageSync
wx.getStorage是指从本地缓存中异步获取指定key的内容,wx.getStorageSync是wx.getStorage的同步版本。
wx.getStorage({key:"key",success(res){
console.log(res.data)
}
})
try{
var value=wx.getStorageSync("key")
if(value){
}
}catch(e){
}
4.4.4wx.getStorageInfo和wx.getStorageInfoSync
wx.getStorageInfo用于异步获取当前storage的相关信息,wx.getStorageInfoSync是wx.getStorageInfo的同步版本。
wx.getStorageInfo({
success(res){
console.log(res.keys)
console.log(res.currentSize)
console.log(res.limitSize)
}
})
try{
const res=wx.getStorageInfoSync()
console.log(res.keys)
console.log(res.currentSize)
console.log(res.limitSize)
}catch(e){
}
4.4.5wx.clearStorage和wx.clearStorageSync
清理本地缓存,wx.clearStorageSync()是wx.clearStorage的同步版本
wx.clearStorage()
try{
wx.clearStorageSync()
}catch(e){
}
4.4.6wx.setBackgroundFetchToken和wx.getBackgroundFetchToken
wx.setBackgroundFetchToken用于设置自定义登录态,在周期性拉取数据时带上,便于第三方服务器验证请求合法性
wx.getBackgroundFetchToken用于获取设置过的自定义登录态,若没有则返回fail
App({
onLaunch() {
wx.setBackgroundFetchToken({
token: 'xxx'
})
}
})
wx.getBackgroundFetchToken({
success(res){
console.log(res.token)//自定义登录态
console.log(res.errMsg)//接口调用结果
}
})
4.4.7wx.onBackgroundFetchData和wx.getBackgroundFetchData
wx.onBackgroundFetchData用于收到backgroundFetch数据的回调,监听后台任务的触发。开发者可以在这个方法中编写具体的任务逻辑,比如发起网络请求获取数据、处理一些定时或特定条件下的操作等。
wx.getBackgroundFetchData用于主动获取后台预拉取数据的接口。例如后台任务获取到的新消息、更新的数据等。通常在小程序从后台切换到前台时,可能会调用这个方法来获取后台任务执行的结果并展示给用户。
App({
onLaunch() {
// 监听收到backgroundFetch数据事件
wx.onBackgroundFetchData((res) => {
console.log('监听到数据:', res.fetchedData);
console.log('时间戳:', res.timeStamp);
});
}
});
App({
onLaunch() {
wx.getBackgroundFetchData({
fetchType: 'periodic',
success(res) {
console.log(res.fetchedData) // 缓存数据console.log(res.timeStamp) // 客户端拿到缓存数据的时间戳
}
})
}
})