欢迎光临,了解微信小程序开发,就上易用通!

mpvue开发小程序总结

发布:2018-12-11 08:40浏览: 来源:网络 作者:cola

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函数)

  1. 预授权
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
       }
     }
   })
复制代码
  1. 用户点击 需要授权的操作时(点击的必须是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"
      ]
    }
  ]
}

复制代码





免责声明:本站所有文章和图片均来自用户分享和网络收集,文章和图片版权归原作者及原出处所有,仅供学习与参考,请勿用于商业用途,如果损害了您的权利,请联系网站客服处理。