记录项目特点,主要为小程序,mpvue框架,项目实现的抽取一些公共方法,以及常用小程序api方法
mpvue:
1、多层数据绑定中,无法实时更新,比如,object.obj1.obj2这种三层以上的,赋值的时候不会实时更新,最好重新定义一个新的值,newObject = object.obj1.obj2
2、 小程序路由封装:
//保留当前页面,跳转到应用内的某个页面,使用wx.navigateBack可以返回到原页面。 export const navigateTo = function(url) { console.log(`跳转的链接:${url}`); wx.navigateTo({ url: url, success: () => {}, fail: () => {}, complete: () => {} }) } // //关闭当前页面,跳转到应用内的某个页面。 export const redirectTo = function(url) { console.log(`跳转的链接:${url}`); wx.redirectTo({ url: url, success: () => {}, fail: () => {}, complete: () => {} }) } //回到一级页面。 export const reLaunch = function(url) { console.log(`跳转的链接:${url}`); wx.reLaunch({ url: url, success: () => {}, fail: () => {}, complete: () => {} }) }
3、保存图片到本地的封装
/** * 保存图片到本地 */ export const saveImg = function(str) { let self = this; let img = str.replace(/http:/, "https:") wx.getSetting({ success(res) { if (!res.authSetting['scope.writePhotosAlbum']) { // 接口调用询问 wx.authorize({ scope: 'scope.writePhotosAlbum', success() { saveToPhotosAlbum(img); }, fail() { // 重新打开设置页面 用户之前拒绝了授权 if (res.authSetting['scope.writePhotosAlbum'] == undefined) { valid.showPlugin('提示',`授权失败`) } else { valid.showPlugin(`提示`,`请先授权保存到相册`,()=>{ wx.openSetting({ success: ()=> { saveToPhotosAlbum(img); }, fail: ()=> {} }); },true) } } }) } else { console.log(img); saveToPhotosAlbum(img) } }, fail(res) {} }) } var saveToPhotosAlbum = function(img) { wx.getImageInfo({ src: img, success: function(ret) { var path = ret.path; wx.saveImageToPhotosAlbum({ filePath: path, success(result) { wx.showToast({ title: '保存成功', icon: 'success', duration: 2000 }) } }) } }) }
4、小程序录音方法的实现
4.1、第一步打开录音授权
1 /** 2 * 打开录音授权 3 */ 4 getLuVoice(){ 5 wx.getSetting({ 6 success: res => { 7 console.log(res) 8 if(!res.authSetting['scope.record']){ 9 console.log('21213424') 10 wx.authorize({ 11 scope:'scope.record', 12 success: res => { 13 console.log(res) 14 }, 15 fail: () => { 16 if(res.authSetting['scope.record'] == undefined){ 17 // this.showPlugin('提示','授权失败') 18 }else { 19 this.showPlugin('提示','请重新授权录音',(res)=>{ 20 // console.log(res) 21 wx.openSetting({ 22 success: res => { 23 console.log(res) 24 this.uploadVoice() 25 } 26 }); 27 }) 28 } 29 }, 30 complete: () => {} 31 }); 32 33 }else { 34 this.uploadVoice() 35 } 36 } 37 }); 38 39 },
4.2、录音数据组成:
voice: { state: -1, //0未开始 1录音中 2已完成 film: 0, }, recorderManager: wx.getRecorderManager(); backgroundAudioManager: wx.getBackgroundAudioManager();
4.3、开始执行录音
/** * 开始录语音 */ uploadVoice(){ this.recorderManager.start({ duration: 300000, format:'mp3' }) this.recorderManager.onStart(() => { console.log('recorder start') this.voice.state = 1 this.voice.film = 0 this.timeInterval = setInterval(()=> { this.voice.film++; if (this.voice.film == 300 ) { clearInterval(this.timeInterval); } }, 1000) }) this.recorderManager.onStop((res) => { console.log('recorder stop') this.voice.state = 0 clearInterval(this.timeInterval); console.log(res) this.uploadQN(res) }) this.recorderManager.onFrameRecorded((res) => { this.voice.state = 0 clearInterval(this.timeInterval); console.log(res) this.uploadQN(res) // 这是把获取的录音链接上传到服务器 }) },
4.4、播放录音
/** * 播放录音 */ playAudio(obj,index){ if (this.audioIndex > -1) { this.voiceArr[this.audioIndex].state = 0 } this.backgroundAudioManager.title = 'play'; this.backgroundAudioManager.src = obj.url this.backgroundAudioManager.onPlay(()=>{ console.log('开始播放') this.voiceArr[index].state = 1 // this. }) this.backgroundAudioManager.onPause(()=>{ console.log('播放暂停') this.voiceArr[index].state = 0 }) this.backgroundAudioManager.onTimeUpdate(()=>{ console.log('播放中') console.log(this.backgroundAudioManager.duration) console.log(this.backgroundAudioManager.currentTime) this.voiceArr[index].time = parseInt(this.backgroundAudioManager.duration - this.backgroundAudioManager.currentTime) < 0? 0 : parseInt(this.backgroundAudioManager.duration - this.backgroundAudioManager.currentTime) }) this.backgroundAudioManager.onEnded(()=>{ console.log('播放结束') this.voiceArr[index].state = 0 }) },
注释:这个是把音视频的时间转换方法
/** * 转换音频时长显示 * parseInt(duration/60) 是将秒转换为整分 * duration%60 是取余,也就是整分后剩余的秒 * minute+isM0+sec 就是分:秒(02:14)的格式 */ transTime: function (time) { let duration = parseInt(time); let minute = parseInt(duration / 60); let sec = duration % 60 + ''; let isM0 = ':'; if (minute === 0) { minute = '00'; } else if (minute < 10) { minute = '0' + minute; } if (sec.length === 1) { sec = '0' + sec; } return minute + isM0 + sec },
5、使用扫码场景值进入小程序,解析链接并获取自定义参数
/** * 处理场景值、问号后参数、Storage参数 */ export const handleParameter = function(options) { console.log(`扫码的场景值:${options.scene}`); let sceneObj = new Object; if (options.scene) { let scene = decodeURIComponent(options.scene) let ary = scene.split('#'); for (let i = 0; i < ary.length; i++) { // 以下是自定义参数 根据自己项目需求改动,生成的二维码的参数排列也是这中形式,不然解析对不上 if (i==0) { sceneObj.dId = ary[i] } else if (i==1) { sceneObj.cid = ary[i] } else if (i==2 && ary[i]) { sceneObj.sid = ary[i] } else if (i==3 && ary[i]) { sceneObj.sourceName = ary[i] } else if (i==4 && ary[i]) { sceneObj.shareUserId = ary[i] } else if (i==5 && ary[i]) { sceneObj.shareUserId1 = ary[i] } else if (i==6 && ary[i]) { sceneObj.code = ary[i] } else if (i==7 && ary[i]) { sceneObj.groupId = ary[i] } } } let obj = {}; if (options.dId) { obj.dId = options.dId; wx.setStorageSync('dId',obj.dId) } else if (sceneObj.dId) { console.log(sceneObj) obj.dId = sceneObj.dId wx.setStorageSync('dId',obj.dId) } else if (wx.getStorageSync('dId')){ obj.dId = wx.getStorageSync('dId') } if (options.cid) { obj.cid = options.cid } else if (sceneObj.cid) { obj.cid = sceneObj.cid } if (options.sid) { obj.sid = options.sid } else if (sceneObj.sid) { obj.sid = sceneObj.sid } if (options.sourceName) { obj.sourceName = options.sourceName; wx.setStorageSync('sourceName',obj.sourceName) } else if (sceneObj.sourceName) { getpathway(sceneObj.sourceName) } if (options.shareUserId) { obj.shareUserId = options.shareUserId wx.setStorageSync('shareUserId',obj.shareUserId) } else if (sceneObj.shareUserId) { console.log(sceneObj); obj.shareUserId = sceneObj.shareUserId wx.setStorageSync('shareUserId',obj.shareUserId) } if (options.shareUserId1) { obj.shareUserId1 = options.shareUserId1 wx.setStorageSync('shareUserId1',obj.shareUserId1) } else if (sceneObj.shareUserId1) { obj.shareUserId1 = sceneObj.shareUserId1 wx.setStorageSync('shareUserId1',obj.shareUserId1) } if (options.code) { obj.code = options.code } else if (sceneObj.code) { obj.code = sceneObj.code } if (options.groupId) { obj.groupId = options.groupId } else if (sceneObj.groupId) { obj.groupId = sceneObj.groupId } return obj }
6、快速获取分享的链接,公共方法,并携带参数 注:主要是自己拿来记录的 并不适合用大众
/** * 获取新的分享链接 */ export const getShareLink = function(){ let uInfo = wx.getStorageSync('uInfo'); let shareUserId = wx.getStorageSync('shareUserId'); let shareUserId1 = wx.getStorageSync('shareUserId1'); let link = ""; if (uInfo) { if (shareUserId) { if (shareUserId == uInfo.userId) { if (shareUserId1) { link = `shareUserId=${uInfo.userId}&shareUserId1=${shareUserId1}` } else { link = `shareUserId=${uInfo.userId}` } } else { link = `shareUserId=${uInfo.userId}&shareUserId1=${shareUserId}` } } else { link = `shareUserId=${uInfo.userId}` } } else { if (shareUserId && shareUserId1) { link = `shareUserId=${shareUserId}&shareUserId1=${shareUserId1}` } else { if (shareUserId) { link = `shareUserId=${shareUserId}` } else { link = "" } } } if (link) { if (getoptions().indexOf('?') > -1) { return `${getoptions()}&${link}` } else { return `${getoptions()}?${link}` } } else { return getoptions() } } /** * 新的分享链接 */ var getoptions = function(){ var pages = getCurrentPages() //获取加载的页面 var currentPage = pages[pages.length - 1] //获取当前页面的对象 var url = currentPage.route //当前页面url var options = currentPage.options //如果要获取url中所带的参数可以查看options let specialAty = ['shareUserId','shareUserId1','sourceName','scene'] let aryRe = []; options.dId = options.dId ? options.dId : wx.getStorageSync('dId') let sceneObj = new Object; if (!isEmpty(options)) { if (options.scene) { let scene = decodeURIComponent(options.scene) let ary = scene.split('#'); for (let i = 0; i < ary.length; i++) { if (i==0) { sceneObj.dId = ary[i] } else if (i==1) { sceneObj.cid = ary[i] } else if (i==2 && ary[i]) { sceneObj.sid = ary[i] } else if (i==3 && ary[i]) { sceneObj.sourceName = ary[i] } else if (i==4 && ary[i]) { sceneObj.shareUserId = ary[i] } else if (i==5 && ary[i]) { sceneObj.shareUserId1 = ary[i] } else if (i==6 && ary[i]) { sceneObj.code = ary[i] } } } if (!isEmpty(sceneObj)) { if (sceneObj.sourceName) { getpathway(sceneObj.sourceName) } options = sceneObj } for (var variable in options) { if (!specialAty.includes(variable)) { if (options.hasOwnProperty(variable)) { aryRe.push(`${variable}=${options[variable]}`) } } } } if (aryRe.length > 0) { url += `?${aryRe.join('&')}` } if (getSourceName()) { if (url.indexOf('?') > -1) { return `/${url}&${getSourceName()}` } else { return `/${url}?${getSourceName()}` } } else { return `/${url}` } } /** * 获取渠道 */ export const getpathway = function(sourceName){ flyGet(_url.GER_PATHWAY, { pathwayId: sourceName }, (res) => { if (res.data.code == 1000 && res.data.result) { let ary = res.data.result; wx.setStorageSync('sourceName',ary.pathwayId) } }) } /** * 获取本人的sourceName */ var getSourceName = function(){ let uInfo = wx.getStorageSync('uInfo'); if (uInfo && uInfo.vipSourceName) { return `sourceName=${uInfo.vipSourceName}` } else if (wx.getStorageSync('sourceName')) { return `sourceName=${wx.getStorageSync('sourceName')}` } else { return "" } }
记录安卓手机的一些问题:
1、在小程序弹窗的时候,安卓手机点击手机的返回,可以把弹窗消失,如果在做一些限制的话,就会无法得到想要的效果,封装弹窗时,在后面多做判断
/** * 显示弹窗 * @return {[type]} [description] */ export const showPlugin = function(title = "提示", content, callback, showCancel = false){ wx.showModal({ title: title, content: content, showCancel: showCancel, success: (res)=> { if (res.confirm) { if (callback) { callback() } }else if(res.cancel){ // 防止安卓手机的返回 callback() }else { // 防止安卓手机的返回 callback() } } }) }
js基本的正则判断:https://mp.weixin.qq.com/s/U1dP7effxMZvLGRa8g5Lrg
7、小程序复制内容:
/** * 设置系统剪贴板的内容 */ export const clipboard = function(data){ wx.setClipboardData({ data: data, success: (res)=> { wx.showToast({ title: '内容已复制', icon: 'success', duration: 2000 }) }, fail: (res)=>{ wx.showToast({ title: `复制失败!`, icon: 'none', duration: 2000 }) } }) }
8、小程序预览图片
/** * 预览图片 */ export const previewImg = function(current,urls){ console.log(urls); wx.previewImage({ current: current, // 当前显示图片的http链接 urls: urls?urls:[current] // 需要预览的图片http链接列表 }) }
9、canvas实现画图、画海报,其中文字换行,头像圆形,渲染文字的方法
/** * 文本换行 * @param {Object} obj */ export const textWrap = function(obj){ let tr = getTextLine(obj); for (let i = 0; i < tr.length; i++) { if (i < obj.line){ let txt = { context: obj.context, x: obj.x, y: obj.y + (i * obj.height), color: obj.color, size: obj.size, align: obj.align, baseline: obj.baseline, text: tr[i], bold: obj.bold }; if (i == obj.line - 1) { if (tr.length > obj.line) { txt.text = txt.text.substring(0, txt.text.length - 1) + '...'; } } drawText(txt); } } } /** * 渲染文字 * * @param {Object} obj */ var drawText = function (obj) { obj.context.save(); obj.context.setFillStyle(obj.color); obj.context.setFontSize(obj.size); obj.context.setTextAlign(obj.align); obj.context.setTextBaseline(obj.baseline); if (obj.bold) { obj.context.fillText(obj.text, obj.x, obj.y - 0.5); obj.context.fillText(obj.text, obj.x - 0.5, obj.y); } obj.context.fillText(obj.text, obj.x, obj.y); if (obj.bold) { obj.context.fillText(obj.text, obj.x, obj.y + 0.5); obj.context.fillText(obj.text, obj.x + 0.5, obj.y); } obj.context.restore(); } /** * 获取文本折行 * @param {Object} obj * @return {Array} arrTr */ var getTextLine = function(obj){ obj.context.setFontSize(obj.size); let arrText = obj.text.split(''); let line = ''; let arrTr = []; for (let i = 0; i < arrText.length; i++) { var testLine = line + arrText[i]; var metrics = obj.context.measureText(testLine); var width = metrics.width; if (width > obj.width && i > 0) { arrTr.push(line); line = arrText[i]; } else { line = testLine; } if (i == arrText.length - 1) { arrTr.push(line); } } return arrTr; } /** * 圆形头像 */ export const circleImg = function(context, img, x, y, r){ context.save(); var d = 2 * r; var cx = x + r; var cy = y + r; context.beginPath(); context.arc(cx, cy, r, 0, 2 * Math.PI); context.clip(); context.drawImage(img, x, y, d, d); context.restore() }