小程序缓存个人头像
开发小程序项目,有时候要对一些信息、图片 进行缓存。
<view class="img-container">
<image wx:if="{{hidden}}" class="head-img" src="{{photoPath}}"></image>
</view>
1. 首先从接口获取头像信息,使用wx.downloadFile下载文件资源到本地,使用wx.saveFile保存文件到本地
wx.downloadFile({
url: '', // 网络返回的图片地址
fail:function(err){
console.log(err)
},
success: function (res) {
// console.log(res.tempFilePath, "下载路径");
wx.saveFile({
tempFilePath: res.tempFilePath,
success: function (res) {
// console.log(res.savedFilePath,"保存路径");
wx.setStorageSync("photoPath", res.savedFilePath)
}
})
}
})
2. 再次进入加载时,需要判断本地是否有缓存在,如果有则先加载缓存的头像,再去请求接口。
if (wx.getStorageSync("photoPath")){
wx.getImageInfo({
src: wx.getStorageSync("photoPath"),
success: function (res) {
me.setData({
photoPath: res.path
})
}
})
}
小知识:
在wxml中只有用text标签包裹的文本才能在手机上长按选中
小程序的自适应单位是rpx,一般情况下不要使用px
|