数据缓存

uni.setStorage
官方文档:https://uniapp.dcloud.io/api/storage/storage?id=setstorage
将数据存储在本地缓存中指定的key中,会覆盖掉原来该key对应的内容,这是一个异步接口。
代码演示:

  1. <template>
  2. <view>
  3. <button @click="getApi">发送get请求</button>
  4. <button type="primary" @click='setStorge'>存储数据</button>
  5. <button type="default" @click='getStorge'>获取数据</button>
  6. <button type="default" @click='removeId'>移除数据</button>
  7. <view>
  8. 这是列表页面
  9. </view>
  10. <view v-for="(item,index) in list" :key='index'>{{item}}<br></view>
  11. <button type="default" @click="pullDown">下拉刷新</button>
  12. </view>
  13. </template>
  14. <script>
  15. export default {
  16. data() {
  17. return {
  18. list:['前端','JAVA','UI','测试','大数据']
  19. }
  20. },
  21. onPullDownRefresh() {
  22. console.log('触发了下拉刷新')
  23. setTimeout(()=>{
  24. this.list = ['JAVA','UI','测试','大数据','前端'] //下拉刷新更新了数据,但是还在不停刷新
  25. uni.stopPullDownRefresh()
  26. },2000) //加了一个延时2秒
  27. },
  28. onReachBottom(){
  29. console.log('页面触底了')
  30. this.list = [...this.list,...['JAVA1','UI1','测试1','大数据1','前端1']]
  31. },
  32. methods: {
  33. pullDown(){
  34. //点击按钮触发下拉刷新
  35. uni.startPullDownRefresh()
  36. },
  37. getApi(){
  38. uni.request({
  39. url:'http://localhost:8082/api/getlunbo',
  40. success(res){
  41. console.log(res.data.message)
  42. }
  43. })
  44. },
  45. //存储数据
  46. setStorge(){
  47. // uni.setStorage({
  48. // key:'id',
  49. // data:80,
  50. // success(){
  51. // console.log('存储成功')
  52. // }
  53. // })
  54. //第二种方法
  55. uni.setStorageSync('id',110)
  56. },
  57. //获取数据
  58. getStorge(){
  59. // uni.getStorage({
  60. // key:'id',
  61. // success(res){
  62. // console.log("获取成功",res.data)
  63. // }
  64. // })
  65. //第二种方法
  66. const res = uni.getStorageSync('id')
  67. console.log(res)
  68. },
  69. //移除数据
  70. removeId(){
  71. // uni.removeStorage({
  72. // key:'id',
  73. // success(){
  74. // console.log('移除成功')
  75. // }
  76. // })
  77. //第二种方法
  78. uni.removeStorageSync('id')
  79. }
  80. }
  81. }
  82. </script>
  83. <style>
  84. </style>

image.png

这里主要讲了 存储数据 获取数据 以及移除数据 三种方式

具体的可以看上面的代码