详解mpvue开发小程序小总结
程序员文章站
2022-07-03 21:35:06
最近用mpvue开发了一个小程序,现总结一下碰见的问题及解决方案
1.项目中数据请求用到了fly.io,封装成request.js如下:
import wx...
最近用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.使用腾讯云存储上传图片
项目中使用了
封装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) }) }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: 那一刻我就决定选你了