数据缓存推荐使用 Sync 同步缓存,更多缓存方法请查看 uniapp 官网:https://uniapp.dcloud.io/api/storage/storage?id=setstorage
将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个异步接口。
OBJECT 参数说明
参数名类型必填说明keyString是本地缓存中的指定的 keydataAny是需要存储的内容,只支持原生类型、及能够通过 JSON.stringify 序列化的对象successFunction否接口调用成功的回调函数failFunction否接口调用失败的回调函数completeFunction否接口调用结束的回调函数(调用成功、失败都会执行)示例:
<template> <view> <button @click="setStorage">存储数据</button> </view> </template> <script> export default { data() { return {} }, methods: { setStorage() { uni.setStorage({ key: 'id', data: 10, success() { console.log("存储成功") } }) } }, } </script> <style> </style>将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口。
参数说明
参数名类型必填说明keyString是本地缓存中的指定的 keydataAny是需要存储的内容,只支持原生类型、及能够通过 JSON.stringify 序列化的对象示例:
<template> <view> <button @click="setStorage">存储数据</button> </view> </template> <script> export default { data() { return {} }, methods: { setStorage() { uni.setStorageSync('id',10) } }, } </script> <style> </style>从本地缓存中异步获取指定 key 对应的内容。
OBJECT 参数说明
参数名类型必填说明keyString是本地缓存中的指定的 keysuccessFunction是接口调用的回调函数,res = {data: key对应的内容}failFunction否接口调用失败的回调函数completeFunction否接口调用结束的回调函数(调用成功、失败都会执行)success 返回参数说明
参数名类型说明dataAnykey 对应的内容示例
<template> <view> <button @click="getStorage">获取数据</button> </view> </template> <script> export default { data() { return {} }, methods: { getStorage(){ uni.getStorage({ key:'id', success(res){ console.log('获取成功',res) } }) } }, } </script> <style> </style>从本地缓存中同步获取指定 key 对应的内容。
参数说明
参数名类型必填说明keyString是本地缓存中的指定的 key示例
<template> <view> <button @click="getStorage">获取数据</button> </view> </template> <script> export default { data() { return {} }, methods: { getStorage(){ const res = uni.getStorageSync('id') console.log(res) } }, } </script> <style> </style>从本地缓存中异步移除指定 key。
OBJECT 参数说明
参数名类型必填说明keyString是本地缓存中的指定的 keysuccessFunction是接口调用的回调函数failFunction否接口调用失败的回调函数completeFunction否接口调用结束的回调函数(调用成功、失败都会执行)示例
<template> <view> <button @click="removeStorage">移除数据</button> </view> </template> <script> export default { data() { return {} }, methods: { removeStorage(){ uni.removeStorage({ key:'id', success() { console.log('删除成功') } }) } }, } </script> <style> </style>从本地缓存中同步移除指定 key。
参数说明
参数名类型必填说明keyString是本地缓存中的指定的 key示例
<template> <view> <button @click="removeStorage">移除数据</button> </view> </template> <script> export default { data() { return {} }, methods: { removeStorage(){ uni.removeStorageSync('id') } }, } </script> <style> </style>