1 <template> 2 <view> 3 4 </view> 5 </template> 6 7 <script> 8 var_self; 9 export default{ 10 data() { 11 return{ 12 13 } 14 }, 15 methods: { 16 17 }, 18 onLoad() { 19 //数据缓存 异步 20 _self = this; 21 uni.setStorage({ 22 key:'name', 23 data:'hcoder', 24 success() { 25 console.log('成功了') 26 }, 27 fail() { 28 console.log('缓存失败了') 29 } 30 }); 31 32 //数据缓存 同步 一定要用try catch 包裹 33 try{ 34 uni.setStorageSync('age', '18'); 35 }catch(e){ 36 //TODO handle the exception 37 }; 38 39 //从本地缓存中 异步获取指定 key 对应的内容 40 uni.getStorage({ 41 key: 'name', 42 success: function(res) { 43 console.log('name 异步获取 = ' +res.data); 44 } 45 }); 46 47 //同步方式获取数据, 阻塞形式,如果做完了的话代码才会向下进行 48 try{ 49 const value =uni.getStorageSync('name'); 50 if(value){ 51 console.log("const value = uni.getStorageSync('name') 同步获取 = " +value) 52 } 53 }catch(e){ 54 //TODO handle the exception 55 }; 56 57 58 //异步获取当前 storage 的相关信息 59 uni.getStorageInfo({ 60 success: function(res) { 61 //keys: 当前 storage 中所有的 key 62 //currentSize: 当前占用的空间大小, 单位:kb current:当前的 63 //limitSize: 限制的空间大小, 单位:kb limit:限制 64 console.log('异步获取' +res.keys); 65 console.log(res.currentSize); 66 console.log(res.limitSize); 67 } 68 }); 69 70 //同步获取 当前 storage 的相关信息 71 try{ 72 const res =uni.getStorageInfoSync(); 73 console.log('同步获取' +res.keys); 74 console.log(res.currentSize); 75 console.log(res.limitSize); 76 } catch(e) { 77 //error 78 }; 79 80 //从本地缓存中 异步移除指定 key 81 //uni.removeStorage({ 82 //key: 'name', 83 //success: function (res) { 84 //console.log('删除成功'); 85 //} 86 //}); 87 88 //从本地缓存中 同步移除指定 key 89 //try { 90 //uni.removeStorageSync('name'); 91 //} catch (e) { 92 //// error 93 //} 94 95 //异步清理本地数据缓存 96 //uni.clearStorage(); 97 // 98 // 99 //// 同步清理本地数据缓存 100 //try { 101 //uni.clearStorageSync(); 102 //} catch (e) { 103 //// error 104 //} 105 } 106 } 107 </script> 108 109 <style> 110 111 </style>
uni-app 数据缓存(setStorage)
免责声明:文章转载自《uni-app 数据缓存(setStorage)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。
宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=