【微信小程序】开发实战 之 「数据缓存API」解析

每个小程序都可以有自己的本地缓存,可以通过 数据缓存的API 实现对本地缓存进行 设置、获取和清理。本地缓存最大为10M。localStorage是永久存储的,但我们不建议将关键信息都放在localStorage,以防用户更换设备。

设置本地缓存

1、wx.setStorage(OBJECT)

该接口是异步接口,用于将数据存储在本地缓存中指定的key中。会覆盖掉该key对应的原来的内容。

该接口参数:

参数key,     string类型,         必填项,本地缓存中指定的key。

参数data,   object/string类型,必填项,需要存储的内容。

参数success,fail,complete,均为Function类型,分别对应接口调用成功、失败和结束时的回调函数。

示例代码如下:

wx.setStorage({
    key:"key",
    data:"value"
})

2、wx.setStorageSync(KEY,DATA)

该接口是同步接口,用于将data存储在本地缓存中指定的key中。会覆盖掉该key对应的原来的内容。

该接口参数:

参数key,     string类型,         必填项,本地缓存中指定的key。

参数data,   object/string类型,必填项,需要存储的内容。

示例代码如下:

try{
    wx.setStorageSync('key', 'value')
}catch(e) {
}

获取/删除 本地缓存

1、wx.getStorage (OBJECT) 和 wx.removeStroage (OBJECT)

wx.getStorage (OBJECT) 用于从本地缓存中异步获取指定key对应的内容。

wx.removeStroage (OBJECT) 用于从本地缓存中异步删除指定key对应的内容。

该接口参数:

参数key,          string类型,          必填项,本地缓存中指定的key。

参数success,   Function类型,      必填项,接口调用成功时的回调函数,res = {data: key 对应的内容}

参数fail,        Function类型,      非必填,接口调用失败时的回调函数

参数complete,  Function类型,      非必填,接口调用结束时的回调函数(调用成功或失败都会执行)

示例代码如下:

wx.getStorage({
    key: 'key',
    success: function(res) {
        console.log(res.data)
    }
});


wx.removeStorage({
    key: 'key',
    success: function(res) {
        console.log(res.data)
    }
})

2、wx.getStorageSync (KEY) 和 wx.removeStroageSync (KEY)

wx.getStorage (KEY) 用于从本地缓存中同步获取指定key对应的内容。

wx.removeStroage (KEY) 用于从本地缓存中同步删除指定key对应的内容。

参数为key,必填项,是本地缓存中的指定的key。

var value = wx.getStorage('key')
if (value) {
    //Do something with return value 
}

try {
    wx.removeStorageSync('key')
} catch(e) {
    //Do something when catch error 
}

获取当前storage的相关信息

1、wx.getStorageInfo (OBJECT)

该接口用于异步获取当前storage的相关信息。

该接口参数:

参数success(必填)、fail、complete,分别对应接口调用成功、失败和结束时的回调函数。其中success是必填项。

success返回参数说明如下:

keys,Sting Array类型,返回storage中所有key。

currentSize,Number类型,表示当前占用的空间大小,单位为kb。

limitSize,Number类型,表示限制的空间大小,单位为kb。

示例代码如下:

wx.getStorageInfo({
    success:function(res) {
        console.log(res.keys)
        console.log(res.currentSize)
        console.log(res.limitSize)
    }
})

2、wx.getStorageInfoSync()

该接口用于同步获取当前storage相关信息。

示例代码如下

try {
    var res = wx.getStorageInfo() 
    console.log( res.keys )
    console.log( res.currentSize )
    console.log( res.limitSize )
} catch (e) { 
    // Do something when catch error
}

清理数据缓存

1、wx.clearStorage()

该接口用于清理本地数据缓存。

2、wx.clearStorageSync()

该接口则用于同步清理本地数据缓存。

示例代码如下:

wx.clearStorage()

try {
    wx.clearStorageSync() 
} catch(e) {
}

 

posted @ 2019-06-09 20:37  DreamGo  阅读(1262)  评论(0编辑  收藏  举报