通用方法(模块化)
- ajax请求: wx.request()
// wx.request 封装 post: function(url = '', json, cb = () => {}, cbErr) { var _this = this var token = '' let userInfo = wx.getStorageSync('userInfo') wx.getStorage({ key: 'token', success: function(res) { token = res.data json.token = token json.business_no = business_no wx.request({ url: _this.globalData.web_url + url, header: { 'content-type': 'application/x-www-form-urlencoded' }, method: 'POST', data: json, success: function(res) { if (res.data.code == 200) { cb(res) } else if (res.data.code == 301) { _this.handleLogin(userInfo) } else if (res.data.code == 41000) { wx.showToast({ title: res.data.msg || '操作失败,请稍后再试', icon: 'none', duration: 2000 }) } }, fail: function(err) { console.log('err:', err) wx.showToast({ title: err || '操作失败,请稍后再试', icon: 'none', duration: 2000 }) } }) } }) },复制代码
- 日期时间格式化: dateFormat()
// 格式化整数 formatNumber(n) { n = n.toString() return n[1] ? n : '0' + n }, // 格式化时间日期 formatTime(date, format = 'yyyy-mm-dd hh:mm') { var _this = this var date = date * 1000 if (date) { const year = new Date(date).getFullYear() const month = new Date(date).getMonth() + 1 const day = new Date(date).getDate() const hour = new Date(date).getHours() const minute = new Date(date).getMinutes() const second = new Date(date).getSeconds() if (format == 'yyyy-mm-dd') { return [year, month, day].map(_this.formatNumber).join('/') } else { return ( [year, month, day].map(_this.formatNumber).join('/') + ' ' + [hour, minute].map(_this.formatNumber).join(':') ) } } }, 复制代码
- 获取设备型号
//获取设备型号 getDevice() { wx.getSystemInfo({ success: function(res) { console.log('device-model:', res) if (res.model.indexOf('iPhone X') != -1) { this.globalData.deviceType = 1 console.log('deviceType324234', _this.globalData.deviceType) } } }) },复制代码
数据存储
关于同步缓存和异步缓存的区别
以Sync(同步,同时)结尾的都是都是同步缓存,二者的区别是,异步不会阻塞当前任务,同步缓存直到同步方法处理完才能继续往下执行。
异步缓存
wx.setStorage({ key:'token', data: '231321313123'})wx.getStorage({ key:'token', success: function(res){ console.log(res.data) }})wx.removeStorage({ key: 'token', success: function(res){ cosnole.log(res.data) } })复制代码
小程序合成图片文字并保存到本地
技术点:
- canvas【wx.drawImage(), wx.fillText(), wx.draw()】
- wx.canvasToTempFilePath(false,callback) // 把当前画布指定区域的内容导出生成指定大小的图片,并返回文件路径
- wx.saveImageToPhotosAlbum() //将文件保存到本地相册,注意要在图片生成的回调函数中执行
注意问题:
真机调试的时候,图片如果是网络图片会显示不出来,需要先调用wx.downloadFile将图片缓存下来
或者直接将图片放在本地再进行合成
页面:
复制代码
效果图:
小程序但参数分享(邀请有礼)
Page({ onShareAppMessage: function (res) { if (res.from === 'button') { // 来自页面内转发按钮 console.log(res.target) } return { title: '自定义转发标题', path: '/page/user?id=123' } }})复制代码
可以将需要携带的参数放在path的页面参数中,然后在页面的onload(options)方法中的options获取
分享时小程序封面图片:
imageUrl | 自定义图片路径,可以是本地文件路径、代码包文件路径或者网络图片路径,支持PNG及JPG,不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4 |
小程序基础库版本与微信客户端版本的关系
小程序的能力需要微信客户端来支撑,每一个基础库都只能在对应的客户端版本上运行,高版本的基础库无法兼容低版本的微信客户端。
以微信 6.5.8 为例,客户端在发布时携带的是 1.1.1 基础库(6.5.7 上已全量的稳定版)发布,在 6.5.8 发布后,我们再通过后台灰度 1.2.0 基础库。
目前小程序开发文档中很多的组件都是基于版本库最低1.4.0的,所以建议设置线上最低基础库为1.4.0