uniapp本地存储

uniapp本地存储

vue的本地存储方式, 小程序在浏览器测试时也可以实现, 但是在真机运行时不能实现

一. 存储

1.uni.setStorage(OBJECT)

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

  • OBJECT参数
  • 示例
    uni.setStorage({
        key:"token",
        data:'123456789',
        success: function (){
            console.log("存储成功")
        }
    })
    

    2.uni.setStorageSync(KEY, DATA)

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

try{
    uni.setStorageSync('token', '123456')
} catch (e){
    //错误
}

二. 获取

  1. uni.getStorage(OBJECT)

 从本地存储中异步获取对应可以对应的内容

uni.getStorage({
    key:"token",
    success: function(res){
        console.log(res.data); //123456789
    }
})

2.uni.getStorageSync(KEY)

从本地缓存中同步获取指定key对应的内容

try {
    const value = uni.getStorageSync("token");
    if(value) {
        console.log(value)
    }
} catch(e){
    //错误
}

3.uni.getStorageInfo(OBJECT)

异步获取当前Storage的相关信息

  • success 返回参数说明

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

4.uni.getStorageInfoSync()

同步获取当前storage的相关信息

try {
    const res = uni.getStorageInfoSync();
    console.log(res.keys);
    console.log(res.currentSize);
    console.log(res.limitSize);
} catch (e) {
    // 错误
}

三. 移除

  1. uni.removeStorage(OBJECT)

从本地缓存中异步移除指定key

uni.removeStorage({
    key:'token',
    success: function(res){
        console.log('删除成功')
    }
})

2 . uni.removeStorageSync(KEY)

从本地缓存中同步移除指定key

try {
    uni.removeStorageSync('storage_key')
} catch(e){
    //错误
}

3.uni.clearStorage()

清除本地缓存

uni.clearStorage();

 4.uni.clearStorageSync()

同步清理本地数据缓存

try {

	uni.clearStorageSync();

} catch (e) {

	//错误

}

猜你喜欢

转载自blog.csdn.net/xybhua/article/details/129175027