微信小程序的缓存问题小知识

1,缓存小demo

方法顺序也是执行顺序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
onShow: function () {
this.getcity();
},
//把城市数据放到缓存中
getcity: function () {
var t = this;
wx.getStorage({
key: 'city',
success: function (res) {
console.log(res.data);
if (res.data) {
t.setData({
city: res.data
})
t.calcDistance();
} else {
t.calcDistance();
}

}
});

},
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
calcDistance: function () {
var t = this;
wx.getLocation({
type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
success: function (res) {
var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180

t.setData(
{

latitude: latitude,
longitude: longitude,
}
)
//获得缓存
wx.getStorage({
key: 'city',
success: function (res) {
console.log(res.data);
if (res.data) {
t.getMainInfo();
t.get_Device_list();
} else {
t.loadCity(longitude, latitude);
}

}
});

}
});
},
loadCity: function (longitude, latitude) {
var t = this
wx.request({
url: 'https://api.map.baidu.com/geocoder/v2/?ak=Nxy41sAxhBwZC0PbbICoq0qHyaTuhDZY&location=' + latitude + ',' + longitude + '&output=json',//百度地图
data: {},
header: {
'Content-Type': 'application/json'
},
success: function (res) {
console.log(res);
var city = res.data.result.addressComponent.city;
//把数据放缓存中
wx.setStorageSync('city', city)
t.setData({
city: city
})
t.getMainInfo();
t.get_Device_list();

},
fail: function () {
t.setData({ currentCity: "获取定位失败" });
},

})
},