本篇博客主要讲的是对小程序进行分享以及对本地数据的存储。
其实分享功能相对来说比较简单,而且课程的实验上也要求实现分享功能。它主要是在index页面中定义一个onShareAppMessage函数,里面要给出分享的标题,页面路径,以及分享图标。
index.js中的代码如下
onShareAppMessage (res) {
let shareInfo = this.data.shareInfo
return {
title: shareInfo.title || '和风天气OUC',
path: shareInfo.path || '/pages/index/index',
imageUrl: shareInfo.imageUrl,
}
},
wxml代码
<view class="usermotto carDesc carDesc1">
<!-- <button class="user-motto share">{{motto}}</button> -->
<button class='share user-motto' id="shareBtn" open-type="share" hover-class="other-button-hover">
{{motto}}
</button>
</view>
最终效果图:
微信官方规定,每个小程序最多可以储存10M的缓存,在本次项目的小程序中,也用到了数据的缓存功能。微信小程序为数据的缓存提供了专门的文件API,用的时候只要调用API就好了。微信小程序官方提供了插入、读取、删除、清空、获取缓存信息的API,具体如下。
操作 | 异步方法 | 同步方法 |
---|---|---|
插入 | wx.setStorage | wx.setStorageSync |
读取 | wx.getStorage | wx.getStorageSync |
删除 | wx.removeStorage | wx.removeStorageSync |
清空 | wx.clearStorage | wx.clearStorageSync |
获取缓存信息 | wx.getStorageInfo | wx.getStorageInfoSync |
存储数据的代码如下
wx.getStorage({
key: 'bcgImgIndex',
success: (res) => {
let bcgImgIndex = res.data || 0
this.setData({
bcgImgIndex,
bcgImg: this.data.bcgImgList[bcgImgIndex].src,
bcgColor: this.data.bcgImgList[bcgImgIndex].topColor,
})
this.setNavigationBarColor()
},
fail: () => {
this.setData({
bcgImgIndex: 0,
bcgImg: this.data.bcgImgList[0].src,
bcgColor: this.data.bcgImgList[0].topColor,
})
this.setNavigationBarColor()
},
})
},
initSetting (successFunc) {
wx.getStorage({
key: 'setting',
success: (res) => {
let setting = res.data || {}
this.setData({
setting,
})
successFunc && successFunc(setting)
},
fail: () => {
this.setData({
setting: {},
})
},
})
},