在使用微信小程序的时候当获取接口的数据的时候,接口传输过来的数据很大,而每一次回到这个页面又再一次的查询获取数据,这难免会拖垮小程序的速度。这个时候就需要使用本地存储。
将数据存储到本地
1 2
| wx.setStorageSync('cates', {time:Date.now, data: this.Cates});
|
获取本地数据
在onLoad函数里面,使用以下代码进行获取数据:使用方法直接获取存储的数据。
1 2
| const Cates = wx.getStorageSync('cates')
|
页面加载时
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| onLoad(options) { const Cates = wx.getStorageSync('cates'); if(!Cates) { this.getCates(); } else { if(Date.now-Cates.time>1000*10) { this.getCates(); } else { this.Cates = Cates.data;
let leftMenuList = this.Cates.map(v=>v.cat_name); let rightContent = this.Cates[0].children; this.setData({ leftMenuList, rightContent }) } } },
|
getCates()方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| Cates: [], getCates() { request({ url: 'https://api-hmugo-web.itheima.net/api/public/v1/categories' }).then((response)=> { this.Cates = response.data.message; wx.setStorageSync('cates', {time:Date.now, data: this.Cates});
let leftMenuList = this.Cates.map(v=>v.cat_name); let rightContent = this.Cates[0].children; this.setData({ leftMenuList, rightContent }) }) },
handleItemTap(e) { const {index} = e.currentTarget.dataset; let rightContent = this.Cates[index].children; this.setData({ currentIndex: index, rightContent })
},
|
截图:
![](/../images/xcx/x1.png)