微信小程序使用本地存储

  1. 1. 将数据存储到本地
  2. 2. 获取本地数据
  3. 3. 页面加载时
  4. 4. getCates()方法
  5. 5. 截图:

在使用微信小程序的时候当获取接口的数据的时候,接口传输过来的数据很大,而每一次回到这个页面又再一次的查询获取数据,这难免会拖垮小程序的速度。这个时候就需要使用本地存储。

将数据存储到本地

1
2
// 把接口中的数据存在本地存储中
wx.setStorageSync('cates', {time:Date.now, data: this.Cates});

获取本地数据

在onLoad函数里面,使用以下代码进行获取数据:使用方法直接获取存储的数据。

1
2
// 1. 获取本地存储中的数据
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) {
// 1. 获取本地存储中的数据
const Cates = wx.getStorageSync('cates');
// 2. 判断是否存在
if(!Cates) {
// 不存在 发送请求获取数据
this.getCates();
} else {
// 有旧数据 定义过期时间 10s
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) {
// console.log(e);
const {index} = e.currentTarget.dataset;
let rightContent = this.Cates[index].children;
this.setData({
currentIndex: index,
rightContent
})

},

截图: