一, 对小程序自身的封装
1.1.wx.request()的 promise 封装(并发请求不能超过五个)
- export const request = (url, data, method) => {
- return new Promise((resolve, reject) => {
- const accessToken = wx.getStorageSync('accessToken')
- const header = {
- 'Content-Type': 'application/json',
- 'token': accessToken // 所有请求将 token 放在 header 里传输
- }
- wx.request({
- url,
- data,
- method,
- success(res) {
- if (res.data.success) {
- resolve(resp)
- } else {
- if(res.data.errorCode === 401) { // token 错误特殊逻辑(code 码跟后端约定)
- const url = "../login/main"
- wx.redirectTo({ url })
- wxToast('登录失效, 请重新登录')
- return
- }
- wxToast(res.errorMessage || '服务异常, 请稍后再试') // 错误统一以 toast 形式弹出
- reject(res.data) // 并将错误抛出以便在 catch 中处理一些特殊业务逻辑
- }
- },
- fail(res) {
- reject(res)
- wxToast(res.errorMessage || '服务异常, 请稍后再试')
- console.log(res)
- }
- })
- })
- }
- // 调用:
- const url = 'https://xxx'
- export const login = params => request(`${url}/xxx`, params, 'POST'); // 登录
- login(params).then(data => {
- console.log('success')
- }).catch(e => {
- console.log('failed')
- })
1.2 toast 的封装
- export const wxToast = (title='',icon='none',duration=2000) => {
- wx.showToast({
- title,
- icon,
- duration
- })
- }
1.3 storage 的封装
- export const wxStorage = (key, data) => {
- if(data) { // data 存在, 则是设置
- wx.setStorage({
- key,
- data
- })
- } else {
- wx.getStorageSync(key)
- }
- }
二, mpvue 小程序采坑
2.1 vue 的 created 钩子
所有页面的 created 钩子在 onLaunch 后就执行了, 所以页面里使用 created 钩子函数是拿不到实时数据的, 故 created 一般情况下不使用. 可用小程序的 onReady 或 onLoad 代替
2.2 vue 的 mounted 钩子
退出再进来页面后 mounted 里的数据并没有重置(页面跳转后并没有销毁页面实例, 而是将其推入页面栈中, 所以会保存之前的旧的数据), 将会导致一系列数据错误, 可用小程序的 onShow 代替(在 onShow 里初始化数据 或者在 onUnLoad 里销毁数据)
2.3 用户拒绝授权后 重新授权
小程序官方已经禁止 主动跳转设置页了, 必须在 button 上触发 (类似获取用户信息 wx.getUserInfo() 首次也是无法主动唤起授权操作, 必须在 button 上绑定 @getuserinfo 函数)
预授权
- const that = this
- wx.getSetting({
- success (res) {
- console.log('点击查询用户录音权限', res.authSetting['scope.record'])
- if (!res.authSetting['scope.record']) {
- // 如果用户之前已经同意授权, 则不会出现弹窗, 直接返回成功
- wx.authorize({
- scope: 'scope.record',
- success () {
- that.isAuth = true
- },
- fail () { // 主动授权失败后引导用户打开权限设置页
- that.isAuth = false
- }
- })
- } else {
- that.isAuth = true
- }
- }
- })
用户点击 需要授权的操作时 (点击的必须是 button, 否则 wx.openSetting() 无法唤起权限设置页)
- if (!this.isAuth) {
- wx.openSetting()
- return
- }
2.4 不支持 template 中使用复杂渲染函数, 可用 computed 计算属性替代
- <template>
- <div> {{format(a)}} </div> // 不支持使用渲染函数 format
- <div>{{b}}</div> // 使用计算属性(若是一个数组列表, 只能先转译数组)
- </template>
- <script>
- export default {
- data() {
- return {
- a:1
- }
- }
- methods: {
- format(e) {
- return `${e}bbb`
- }
- },
- computed: {
- b() {
- return `${this.a}bbb`
- }
- }
- }
- </script>
2.5 class/style 不支持 vue 的 classObject/styleObject, 但支持如下形式:
- <p class="static" :class="{ active: isActive,'text-danger': hasError }">
- 222
- </p>
- <p class="static" :class="[isActive ? activeClass :'', errorClass]">
- 444
- </p>
- :style="{transform:'translate('+ (item.ansId==currentTouchId ? xAxis :
- 0) +'px,'+ ((item.ansId==currentTouchId ? yAxis : 0)) +'px)',width: width
- +'px', height: height +'px'}"
2.6 CSS background-image 不支持本地图片, 必须是远程 cdn 资源
2.7 用 canvas 绘图, 生成带参数的小程序码的海报用于分享朋友圈
由于 海报图是放在 cdn 中, canvas 不能操作不在同一域名下的图片, 故由服务端去合成
2.8 跳转 tabBar 页面必须用 switchTab
2.9 强制更新
- const updateManager = wx.getUpdateManager()
- updateManager.onCheckForUpdate(function (res) {
- // 请求完新版本信息的回调
- console.log(res.hasUpdate)
- })
- updateManager.onUpdateReady(function () {
- wx.showModal({
- title: '更新提示',
- content: '新版本已经准备好, 是否重启应用?',
- success: function (res) {
- if (res.confirm) {
- // 新的版本已经下载好, 调用 applyUpdate 应用新版本并重启
- updateManager.applyUpdate()
- }
- }
- })
- })
2.10 单独为每个页面的设置页面头部信息(main.JS 中设置)
- // main.JS
- const App = new Vue(App)
- App.$mount()
- export default {
- config: {
- navigationBarTitleText: '登录'
- }
- }
2.11 获取扫 带参数二维码用户进来的参数
- onLoad(options) {
- console.log(decodeURIComponent(options.scene))
- }
2.12 小程序 checkbox 点击选中显示错乱
- <checkbox :value="index" :checked="checkItem.checked" />
- // 加上 checked 属性, 点击修改其 boolean 值
2.13 带参数的自定义分享
- <template>
- // 通过 button 触发
- <button open-type="share"></button>
- </template>
- <script>
- onShareAppMessage(res) {
- let id = wx.getStorageSync("id");
- let title = `${this.name}哈哈哈!` // 可以取到 data 中的数据
- let path = "/pages/xxx/main?sourceId=" + id // 必须是以 / 开头的完整路径
- let imageUrl = "https:xxx.jpg" // 默认是截屏
- return {
- title: title,
- path: path,
- imageUrl: imageUrl
- };
- }
- </script>
2.14 获取模板消息 id
- <form :report-submit="true" @submit="onClick">
- <button @click="onShare('students')" class="applyStu" formType="submit">获取 form_id</button>
- </form>
- onClick(e){
- this.formId = e.mp.detail.formId
- }
- // 点击一次获取多个 formId:
- //https://www.jianshu.com/p/84dd9cd6eaed?_blank
2.15 分包与主包的配置
- {
- "pages": [
- "pages/index/main",
- "pages/logs/main"
- ],
- "window": {
- "backgroundTextStyle": "light",
- "navigationBarBackgroundColor": "#fff",
- "navigationBarTitleText": "WeChat",
- "navigationBarTextStyle": "black"
- },
- "subPackages": [
- {
- "root": "pages/subPackages", // 分包根路径
- "pages": [
- "index/main"
- ]
- }
- ]
- }
来源: https://juejin.im/post/5c09d434f265da61441fdaf5