詳解mpvue開(kāi)發(fā)小程序小總結(jié)
最近用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è),用戶登錄態(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) {
// 保存用戶信息相關(guān)操作
...
resolve(res)
} else {
reject(res)
}
}).catch(err => {
reject(err)
})
},
// 若獲取不到用戶信息 (最大可能是用戶授權(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)信息(昵稱、頭像等),請(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)
}
// 名稱定義
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)文章
vue實(shí)現(xiàn)列表垂直無(wú)縫滾動(dòng)
這篇文章主要為大家詳細(xì)介紹了vue實(shí)現(xiàn)列表垂直無(wú)縫滾動(dòng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04
vue el-table字段點(diǎn)擊出現(xiàn)el-input輸入框,失焦保存方式
這篇文章主要介紹了vue el-table字段點(diǎn)擊出現(xiàn)el-input輸入框,失焦保存方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02
vue實(shí)現(xiàn)登錄數(shù)據(jù)的持久化的使用示例
在Vue.js中,實(shí)現(xiàn)登錄數(shù)據(jù)的持久化需要使用瀏覽器提供的本地存儲(chǔ)功能,Vue.js支持使用localStorage和sessionStorage來(lái)實(shí)現(xiàn)本地存儲(chǔ),本文就來(lái)介紹一下如何實(shí)現(xiàn),感興趣的可以了解一下2023-10-10
vue+el使用this.$confirm,不能阻斷代碼往下執(zhí)行的解決
這篇文章主要介紹了vue+el使用this.$confirm,不能阻斷代碼往下執(zhí)行的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09
Vite3結(jié)合Svelte3使用@import導(dǎo)入scss樣式
這篇文章主要為大家介紹了Vite3結(jié)合Svelte3使用@import導(dǎo)入scss樣式實(shí)現(xiàn)實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
vue中axios處理http發(fā)送請(qǐng)求的示例(Post和get)
本篇文章主要介紹了vue中axios處理http請(qǐng)求的示例(Post和get),這里整理了詳細(xì)的代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10
前端VUE雙語(yǔ)實(shí)現(xiàn)方案詳細(xì)教程
在項(xiàng)目需求中我們會(huì)遇到國(guó)際化的中英文切換,這篇文章主要給大家介紹了關(guān)于前端VUE雙語(yǔ)實(shí)現(xiàn)方案的相關(guān)資料,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-08-08
關(guān)于vue利用postcss-pxtorem進(jìn)行移動(dòng)端適配的問(wèn)題
這篇文章主要介紹了關(guān)于vue利用postcss-pxtorem進(jìn)行移動(dòng)端適配的問(wèn)題,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
Vue實(shí)現(xiàn)網(wǎng)頁(yè)首屏加載動(dòng)畫(huà)及頁(yè)面內(nèi)請(qǐng)求數(shù)據(jù)加載loading效果
Loading加載動(dòng)畫(huà)組件看起來(lái)很簡(jiǎn)單不重要,實(shí)際上它是保證用戶留存的關(guān)鍵一環(huán),下面這篇文章主要給大家介紹了關(guān)于Vue實(shí)現(xiàn)網(wǎng)頁(yè)首屏加載動(dòng)畫(huà)及頁(yè)面內(nèi)請(qǐng)求數(shù)據(jù)加載loading效果的相關(guān)資料,需要的朋友可以參考下2023-02-02

