欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解mpvue開(kāi)發(fā)小程序小總結(jié)

 更新時(shí)間:2018年07月25日 09:59:02   作者:小小令  
這篇文章主要介紹了詳解mpvue開(kāi)發(fā)小程序小總結(jié),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

最近用mpvue開(kāi)發(fā)了一個(gè)小程序,現(xiàn)總結(jié)一下碰見(jiàn)的問(wèn)題及解決方案

1.項(xiàng)目中數(shù)據(jù)請(qǐng)求用到了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 請(qǐng)求攔截器
fly.interceptors.request.use((config) => {
 wx.showNavigationBarLoading()//導(dǎo)航條加載動(dòng)畫(huà)
 //給所有請(qǐng)求添加自定義header
 if (store.getters.accessToken) {
  config.headers['Authorization'] = `JWT ${store.getters.accessToken}`
 }
 config.headers['X-Tag'] = 'flyio'
 return config
})

//http 響應(yīng)攔截器
fly.interceptors.response.use((response) => {
  wx.hideNavigationBarLoading()//導(dǎo)航條加載動(dòng)畫(huà)
  const res = response.data
  if (res.status === 0 && (res.errCode === 401 || res.errCode === 403)) {
   //跳轉(zhuǎn)到登錄頁(yè)面
   wx.redirectTo({
    url: '/pages/welcome/main',
   })
  }
  return res
 },
 (err) => {
  wx.hideNavigationBarLoading()//導(dǎo)航條加載動(dòng)畫(huà)
  //發(fā)生網(wǎng)絡(luò)錯(cuò)誤后會(huì)走到這里
  return Promise.reject(err.response)
 },
)

export default fly

2.有關(guān)登錄的處理:

這個(gè)項(xiàng)目中用到了一個(gè)登錄頁(yè),用戶(hù)登錄態(tài)失效也會(huì)跳轉(zhuǎn)到登錄頁(yè)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) => {
  // 先調(diào)用 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) {
        // 保存用戶(hù)信息相關(guān)操作
        ...
        resolve(res)
       } else {
        reject(res)
       }
      }).catch(err => {
       reject(err)
      })
     },
     // 若獲取不到用戶(hù)信息 (最大可能是用戶(hù)授權(quán)不允許,也有可能是網(wǎng)絡(luò)請(qǐng)求失敗,但該情況很少)
     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: '重新授權(quán)',
      message: '需要獲取您的公開(kāi)信息(昵稱(chēng)、頭像等),請(qǐng)點(diǎn)擊"微信登錄"進(jìn)行授權(quán)',
      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.使用騰訊云存儲(chǔ)上傳圖片

項(xiàng)目中使用了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

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

// 名稱(chēng)定義
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轉(zhuǎn)換成file文件
export function Base64ToBlob (urlData) {
 // 去掉url的頭,并轉(zhuǎn)換為byte
 let bytes = window.atob(urlData.split(',')[1])

 // 處理異常,將ascii碼小于0的轉(zhuǎn)換為大于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)
  })

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

小程序上傳多圖時(shí)保證圖片均上傳到cos服務(wù)器再執(zhí)行其余操作:

//選擇圖片
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) => {
     //沒(méi)有圖片
     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=>{
    //執(zhí)行剩余步驟
    }).catch(err=>{
     console.log(err)
  })
}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論