亲宝软件园·资讯

展开

mpvue 小程序 详解mpvue开发小程序小总结

小小令 人气:0

最近用mpvue开发了一个小程序,现总结一下碰见的问题及解决方案

1.项目中数据请求用到了fly.io,封装成request.js如下:

import wx from 'wx'
import Fly from 'flyio'
import store from '../store/index'

const fly = new Fly()

fly.config.baseURL = process.env.BASE_URL
fly.config.timeout = 5000

//http 请求拦截器
fly.interceptors.request.use((config) => {
 wx.showNavigationBarLoading()//导航条加载动画
 //给所有请求添加自定义header
 if (store.getters.accessToken) {
  config.headers['Authorization'] = `JWT ${store.getters.accessToken}`
 }
 config.headers['X-Tag'] = 'flyio'
 return config
})

//http 响应拦截器
fly.interceptors.response.use((response) => {
  wx.hideNavigationBarLoading()//导航条加载动画
  const res = response.data
  if (res.status === 0 && (res.errCode === 401 || res.errCode === 403)) {
   //跳转到登录页面
   wx.redirectTo({
    url: '/pages/welcome/main',
   })
  }
  return res
 },
 (err) => {
  wx.hideNavigationBarLoading()//导航条加载动画
  //发生网络错误后会走到这里
  return Promise.reject(err.response)
 },
)

export default fly

2.有关登录的处理:

这个项目中用到了一个登录页,用户登录态失效也会跳转到登录页login.js

import wx from 'wx'
import { loginByCode } from '../api/weAppAuth' //登录接口
import store from '../store'

/**
 * 登录
 * @returns {Promise<any>}
 */
export function weAppLogin () {
 return new Promise((resolve, reject) => {
  // 先调用 wx.login 获取到 code
  wx.login({
   success: (res) => {
    wx.getUserInfo({
     lang: 'zh_CN',
     success: ({rawData, signature, encryptedData, iv, userInfo}) => {
      let data = {
       code: res.code,
       rawData,
       signature,
       encryptedData,
       iv,
       userInfo,
      }
      // console.log(JSON.stringify(data))
      loginByCode(data).then(res => {
       // 该为我们后端的逻辑 若code > 0为登录成功,其他情况皆为异常 (视自身情况而定)
       if (res.status === 1) {
        // 保存用户信息相关操作
        ...
        resolve(res)
       } else {
        reject(res)
       }
      }).catch(err => {
       reject(err)
      })
     },
     // 若获取不到用户信息 (最大可能是用户授权不允许,也有可能是网络请求失败,但该情况很少)
     fail: (err) => {
      reject(err)
     },
    })
   },
  })
 })
}

welcome.vue

 <button
    class="default-btn "
    open-type="getUserInfo"
    @getuserinfo="onGotUserInfo"
    type="primary"
   >
    微信登录
</button>

 methods: {
   //登录
   onGotUserInfo ({mp}) {
    const {detail} = mp
    if (!detail.rawData) {
     Dialog({
      title: '重新授权',
      message: '需要获取您的公开信息(昵称、头像等),请点击"微信登录"进行授权',
      confirmButtonText: '确定',
      confirmButtonColor: '#373737',
     })
    } else {
     weAppLogin().then(res => {
      console.log(res)
      Toast({
       type: 'success',
       message: '登录成功',
       selector: '#zan-toast-test',
       timeout:1000
      })
      setTimeout(() => {
       wx.switchTab({
        url: '/pages/index/main',
       })
      }, 1000)
     }).catch(err => {
      console.log(err)
     })
    }
   },
  },

3.支付方法封装成promise

import wx from 'wx'

/**
 * 支付
 * @param data
 * @returns {Promise<any>}
 */
export function wechatPay (data) {
 const {timeStamp, nonceStr, signType, paySign} = data
 return new Promise((resolve, reject) => {
  wx.requestPayment({
   timeStamp: timeStamp,
   nonceStr: nonceStr,
   package: data.package,
   signType: signType,
   paySign: paySign,
   success: (res) => {
    resolve(res)
   },
   fail: (err) => {
    reject(err)
   },
  })
 })
}

4.使用腾讯云存储上传图片

项目中使用了cos-wx-sdk-v5

封装upload.js方法:

const COS = require('../../static/js/cos-wx-sdk-v5')
import fly from './request'

export const Bucket = process.env.Bucket
export const Region = process.env.Region

// 文件扩展名提取
export function fileType (fileName) {
 return fileName.substring(fileName.lastIndexOf('.') + 1)
}

// 名称定义
export function path(id, type, fileType) {
 const date = new Date()
 const year = date.getFullYear()
 const month = date.getMonth() + 1
 const day = date.getDate()
 var time = date.toTimeString()
 time = time.substr(0, 8)
 time = time.replace(/:/g, '-')
 return `/mobile/groups/${id}/${type}/` +
  (year + '-' + (month < 10 ? '0' + month : String(month)) + '-' +
   (day < 10 ? '0' + day : String(day)) + '-' + time) + '.' + fileType
}

// base64转换成file文件
export function Base64ToBlob (urlData) {
 // 去掉url的头,并转换为byte
 let bytes = window.atob(urlData.split(',')[1])

 // 处理异常,将ascii码小于0的转换为大于0
 let ab = new ArrayBuffer(bytes.length)
 let ia = new Uint8Array(ab)
 for (let i = 0; i < bytes.length; i++) {
  ia[i] = bytes.charCodeAt(i)
 }
 return new Blob([ab], {
  type: 'image/png',
 })
}

export const cos = new COS({
 getAuthorization: (options, callback) => {
  let url = '/qcloud/cos_sign'
  fly.request({
   url: url,
   method: 'post',
   body: {
    method: (options.Method || 'get').toLowerCase(),
    pathname: '/' + (options.Key || ''),
   },
  }).then(res => {
   callback(res.data.authorization)
  }).catch(err => {
   console.log(err)
  })

  //本地测试
  /*let authorization = COS.getAuthorization({
   SecretId: '你的id',
   SecretKey: '你的key',
   Method: options.Method,
   Key: options.Key,
  })
  callback(authorization)*/
 },
})

小程序上传多图时保证图片均上传到cos服务器再执行其余操作:

//选择图片
chooseImage () {
    wx.chooseImage({
     count: this.chooseImageNum,
     sizeType: ['original'],
     sourceType: ['album', 'camera'],
     success: (res) => {
      this.imageList = [...this.imageList, ...res.tempFilePaths]
     },
    })

},

uploadImg (data, index) {
    return new Promise((resolve, reject) => {
     let filePath = data
     let fileName = path(this.id, 'test',
      fileType(filePath.substr(filePath.lastIndexOf('/') + 1))) + index
     cos.postObject({
      Bucket: Bucket,
      Region: Region,
      Key: fileName,
      FilePath: filePath,
     }, (err, res) => {
      if (res.statusCode === 200) {
       let item = {
        imageUrl: res.Location,
       }
       this.data.imageList.push(item)
       resolve(res)
      } else {
       reject(err)
      }
     })

    })
},
//上传图片
 upload () {
    return new Promise((resolve, reject) => {
     //没有图片
     if (this.imageList.length === 0) {
      let data = {
       statusCode: 200,
      }
      resolve(data)
      return
     }
     //有图片
     let all = []
     for (let i = 0; i < this.imageList.length; i++) {
      all.push(this.uploadImg(this.imageList[i], i))
     }
     Promise.all(all).then(res => {
      resolve(res)
     }).catch(err => {
      reject(err)
     })
    })
},

handleSubmit(){
   this.upload().then(res=>{
    //执行剩余步骤
    }).catch(err=>{
     console.log(err)
  })
}

加载全部内容

相关教程
猜你喜欢
用户评论