From b87c062a1c7447b4ae018123557575768a4b0968 Mon Sep 17 00:00:00 2001 From: evoxwht <442384644@qq.com> Date: Wed, 14 Apr 2021 10:33:50 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=B0=8F=E7=A8=8B=E5=BA=8F?= =?UTF-8?q?=E6=8E=88=E6=9D=83=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../xcx/components/authorize/authorize.js | 340 +++--- template/xcx/utils/util.js | 1022 +++++++++-------- 2 files changed, 738 insertions(+), 624 deletions(-) diff --git a/template/xcx/components/authorize/authorize.js b/template/xcx/components/authorize/authorize.js index 4bf6f459a..daf0a904e 100644 --- a/template/xcx/components/authorize/authorize.js +++ b/template/xcx/components/authorize/authorize.js @@ -1,157 +1,193 @@ -import { CACHE_USERINFO, CACHE_TOKEN, CACHE_EXPIRES_TIME } from '../../config.js'; +import { + CACHE_USERINFO, + CACHE_TOKEN, + CACHE_EXPIRES_TIME +} from '../../config.js'; import Util from '../../utils/util.js'; -import { getLogo } from '../../api/api.js'; -import { login } from '../../api/user.js'; +import { + getLogo +} from '../../api/api.js'; +import { + login +} from '../../api/user.js'; let app = getApp(); Component({ - properties: { - iShidden: { - type: Boolean, - value: true, - }, - //是否自动登录 - isAuto: { - type: Boolean, - value: true, - }, - isGoIndex:{ - type: Boolean, - value:true, - }, - }, - data: { - cloneIner: null, - loading:false, - errorSum:0, - errorNum:3, - canIUseGetUserProfile: false // 判断是否为最新获取用户信息函数 - }, - attached() { - this.get_logo_url(); - this.setAuthStatus(); - if (wx.getUserProfile) { - this.setData({ - canIUseGetUserProfile: true - }) - } - }, - methods: { - close(){ - let pages = getCurrentPages(); - let currPage = pages[pages.length - 1]; - if(this.data.isGoIndex){ - wx.switchTab({url:'/pages/index/index'}); - }else{ - this.setData({ - iShidden: true - }); - if (currPage && currPage.data.iShidden != undefined){ - currPage.setData({ iShidden:true}); - } - } - }, - get_logo_url: function () { - var that = this; - if (wx.getStorageSync('logo_url')) return this.setData({ logo_url: wx.getStorageSync('logo_url') }); - getLogo().then(res=>{ - wx.setStorageSync('logo_url', res.data.logo_url); - that.setData({ logo_url: res.data.logo_url }); - }); - }, - //检测登录状态并执行自动登录 - setAuthStatus() { - var that = this; - Util.chekWxLogin().then((res)=> { - let pages = getCurrentPages(); - let currPage = pages[pages.length - 1]; - if (currPage && currPage.data.iShidden != undefined) { - currPage.setData({ iShidden:true}); - } - if (res.isLogin) { - if (!Util.checkLogin()) return Promise.reject({ authSetting: true, msg: '用户token失效', userInfo: res.userInfo}); - that.triggerEvent('onLoadFun', app.globalData.userInfo); - }else{ - wx.showLoading({ title: '正在登录中' }); - that.setUserInfo(res.userInfo,true); - } - }).catch(res=>{ - if (res.authSetting === false) { - //没有授权不会自动弹出登录框 - if (that.data.isAuto === false) return; - //自动弹出授权 - that.setData({ iShidden: false }); - } else if (res.authSetting){ - //授权后登录token失效了 - that.setUserInfo(res.userInfo); - } - }) - }, - // 获取用户信息 - getUserProfile() { - let that = this; - wx.showLoading({ title: '正在登录中' }); - wx.getUserProfile({ - desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写 - success: (res) => { - Util.getCodeLogin((code)=>{ - let userInfo = res; - userInfo.code = code.code; - that.getWxUserInfo(userInfo); - }) - }, - fail: (err) => { - wx.hideLoading(); - } - }); - }, - //授权 - setUserInfo(userInfo,isLogin) { - let that = this; - wx.showLoading({ title: '正在登录中' }); - if (isLogin){ - that.getWxUserInfo(userInfo); - }else{ - Util.getCodeLogin((res)=>{ - Util.wxgetUserInfo().then(userInfo=>{ - userInfo.code = res.code; - that.getWxUserInfo(userInfo); - }).catch(res=>{ - wx.hideLoading(); - }); - }); - } - }, - getWxUserInfo: function (userInfo){ - let that = this; - userInfo.spread_spid = app.globalData.spid;//获取推广人ID - userInfo.spread_code = app.globalData.code;//获取推广人分享二维码ID - login(userInfo).then(res => { - app.globalData.token = res.data.token; - app.globalData.isLog = true; - app.globalData.userInfo = res.data.userInfo; - app.globalData.expiresTime = res.data.expires_time; - wx.setStorageSync(CACHE_TOKEN, res.data.token); - wx.setStorageSync(CACHE_EXPIRES_TIME, res.data.expires_time); - wx.setStorageSync(CACHE_USERINFO, JSON.stringify(res.data.userInfo)); - if (res.data.cache_key) wx.setStorage({ key: 'cache_key', data: res.data.cache_key }); - //取消登录提示 - wx.hideLoading(); - //关闭登录弹出窗口 - that.setData({ iShidden: true, errorSum: 0 }); - //执行登录完成回调 - that.triggerEvent('onLoadFun', app.globalData.userInfo); - }).catch((err) => { - wx.hideLoading(); - that.data.errorSum++; - that.setData({ errorSum: that.data.errorSum }); - if (that.data.errorSum >= that.data.errorNum) { - Util.Tips({ title: err }); - } else { - that.setUserInfo(userInfo); - } - }); - } - }, -}) \ No newline at end of file + properties: { + iShidden: { + type: Boolean, + value: true, + }, + //是否自动登录 + isAuto: { + type: Boolean, + value: true, + }, + isGoIndex: { + type: Boolean, + value: true, + }, + }, + data: { + cloneIner: null, + loading: false, + errorSum: 0, + errorNum: 3, + canIUseGetUserProfile: false // 判断是否为最新获取用户信息函数 + }, + attached() { + this.get_logo_url(); + this.setAuthStatus(); + if (wx.getUserProfile) { + this.setData({ + canIUseGetUserProfile: true + }) + } + }, + methods: { + close() { + let pages = getCurrentPages(); + let currPage = pages[pages.length - 1]; + if (this.data.isGoIndex) { + wx.switchTab({ + url: '/pages/index/index' + }); + } else { + this.setData({ + iShidden: true + }); + if (currPage && currPage.data.iShidden != undefined) { + currPage.setData({ + iShidden: true + }); + } + } + }, + get_logo_url: function() { + var that = this; + if (wx.getStorageSync('logo_url')) return this.setData({ + logo_url: wx.getStorageSync('logo_url') + }); + getLogo().then(res => { + wx.setStorageSync('logo_url', res.data.logo_url); + that.setData({ + logo_url: res.data.logo_url + }); + }); + }, + //检测登录状态并执行自动登录 + setAuthStatus() { + var that = this; + Util.chekWxLogin().then((res) => { + let pages = getCurrentPages(); + let currPage = pages[pages.length - 1]; + if (currPage && currPage.data.iShidden != undefined) { + currPage.setData({ + iShidden: true + }); + } + if (res.isLogin) { + if (!Util.checkLogin()) return Promise.reject({ + authSetting: true, + msg: '用户token失效', + userInfo: res.userInfo + }); + that.triggerEvent('onLoadFun', app.globalData.userInfo); + } else { + wx.showLoading({ + title: '正在登录中' + }); + that.setUserInfo(res.userInfo, true); + } + }).catch(res => { + if (res.authSetting === false) { + //没有授权不会自动弹出登录框 + if (that.data.isAuto === false) return; + //自动弹出授权 + that.setData({ + iShidden: false + }); + } else if (res.authSetting) { + //授权后登录token失效了 + that.setUserInfo(res.userInfo); + } + }) + }, + // 获取用户信息 + getUserProfile() { + let that = this; + wx.showLoading({ + title: '正在登录中' + }); + wx.getUserProfile({ + desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写 + success: (res) => { + Util.getCodeLogin((code) => { + let userInfo = res; + userInfo.code = code.code; + that.getWxUserInfo(userInfo); + }) + }, + fail: (err) => { + wx.hideLoading(); + } + }); + }, + //授权 + setUserInfo(userInfo, isLogin) { + let that = this; + wx.showLoading({ + title: '正在登录中' + }); + if (isLogin) { + that.getWxUserInfo(userInfo); + } else { + wx.hideLoading(); + that.setData({ + iShidden: false + }); + } + }, + getWxUserInfo: function(userInfo) { + let that = this; + userInfo.spread_spid = app.globalData.spid; //获取推广人ID + userInfo.spread_code = app.globalData.code; //获取推广人分享二维码ID + login(userInfo).then(res => { + app.globalData.token = res.data.token; + app.globalData.isLog = true; + app.globalData.userInfo = res.data.userInfo; + app.globalData.expiresTime = res.data.expires_time; + wx.setStorageSync(CACHE_TOKEN, res.data.token); + wx.setStorageSync(CACHE_EXPIRES_TIME, res.data.expires_time); + wx.setStorageSync(CACHE_USERINFO, JSON.stringify(res.data.userInfo)); + if (res.data.cache_key) wx.setStorage({ + key: 'cache_key', + data: res.data.cache_key + }); + //取消登录提示 + wx.hideLoading(); + //关闭登录弹出窗口 + that.setData({ + iShidden: true, + errorSum: 0 + }); + //执行登录完成回调 + that.triggerEvent('onLoadFun', app.globalData.userInfo); + }).catch((err) => { + wx.hideLoading(); + that.data.errorSum++; + that.setData({ + errorSum: that.data.errorSum + }); + if (that.data.errorSum >= that.data.errorNum) { + Util.Tips({ + title: err + }); + } else { + that.setUserInfo(userInfo); + } + }); + } + }, +}) diff --git a/template/xcx/utils/util.js b/template/xcx/utils/util.js index 5795b10dd..7f63c2532 100644 --- a/template/xcx/utils/util.js +++ b/template/xcx/utils/util.js @@ -1,74 +1,104 @@ -import { TOKENNAME } from './../config.js'; +import { + TOKENNAME +} from './../config.js'; const formatTime = date => { - const year = date.getFullYear() - const month = date.getMonth() + 1 - const day = date.getDate() - const hour = date.getHours() - const minute = date.getMinutes() - const second = date.getSeconds() + const year = date.getFullYear() + const month = date.getMonth() + 1 + const day = date.getDate() + const hour = date.getHours() + const minute = date.getMinutes() + const second = date.getSeconds() - return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':') + return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':') } -const $h={ - //除法函数,用来得到精确的除法结果 - //说明:javascript的除法结果会有误差,在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。 - //调用:$h.Div(arg1,arg2) - //返回值:arg1除以arg2的精确结果 - Div:function (arg1, arg2) { - arg1 = parseFloat(arg1); - arg2 = parseFloat(arg2); - var t1 = 0, t2 = 0, r1, r2; - try { t1 = arg1.toString().split(".")[1].length; } catch (e) { } - try { t2 = arg2.toString().split(".")[1].length; } catch (e) { } - r1 = Number(arg1.toString().replace(".", "")); - r2 = Number(arg2.toString().replace(".", "")); - return this.Mul(r1 / r2 , Math.pow(10, t2 - t1)); - }, - //加法函数,用来得到精确的加法结果 - //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。 - //调用:$h.Add(arg1,arg2) - //返回值:arg1加上arg2的精确结果 - Add: function (arg1, arg2) { - arg2 = parseFloat(arg2); - var r1, r2, m; - try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 } - try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 } - m = Math.pow(100, Math.max(r1, r2)); - return (this.Mul(arg1, m) + this.Mul(arg2, m)) / m; - }, - //减法函数,用来得到精确的减法结果 - //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的减法结果。 - //调用:$h.Sub(arg1,arg2) - //返回值:arg1减去arg2的精确结果 - Sub: function (arg1, arg2) { - arg1 = parseFloat(arg1); - arg2 = parseFloat(arg2); - var r1, r2, m, n; - try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 } - try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 } - m = Math.pow(10, Math.max(r1, r2)); - //动态控制精度长度 - n = (r1 >= r2) ? r1 : r2; - return ((this.Mul(arg1, m) - this.Mul(arg2, m)) / m).toFixed(n); - }, - //乘法函数,用来得到精确的乘法结果 - //说明:javascript的乘法结果会有误差,在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。 - //调用:$h.Mul(arg1,arg2) - //返回值:arg1乘以arg2的精确结果 - Mul: function (arg1, arg2) { - arg1 = parseFloat(arg1); - arg2 = parseFloat(arg2); - var m = 0, s1 = arg1.toString(), s2 = arg2.toString(); - try { m += s1.split(".")[1].length } catch (e) { } - try { m += s2.split(".")[1].length } catch (e) { } - return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m); - }, +const $h = { + //除法函数,用来得到精确的除法结果 + //说明:javascript的除法结果会有误差,在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。 + //调用:$h.Div(arg1,arg2) + //返回值:arg1除以arg2的精确结果 + Div: function(arg1, arg2) { + arg1 = parseFloat(arg1); + arg2 = parseFloat(arg2); + var t1 = 0, + t2 = 0, + r1, r2; + try { + t1 = arg1.toString().split(".")[1].length; + } catch (e) {} + try { + t2 = arg2.toString().split(".")[1].length; + } catch (e) {} + r1 = Number(arg1.toString().replace(".", "")); + r2 = Number(arg2.toString().replace(".", "")); + return this.Mul(r1 / r2, Math.pow(10, t2 - t1)); + }, + //加法函数,用来得到精确的加法结果 + //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。 + //调用:$h.Add(arg1,arg2) + //返回值:arg1加上arg2的精确结果 + Add: function(arg1, arg2) { + arg2 = parseFloat(arg2); + var r1, r2, m; + try { + r1 = arg1.toString().split(".")[1].length + } catch (e) { + r1 = 0 + } + try { + r2 = arg2.toString().split(".")[1].length + } catch (e) { + r2 = 0 + } + m = Math.pow(100, Math.max(r1, r2)); + return (this.Mul(arg1, m) + this.Mul(arg2, m)) / m; + }, + //减法函数,用来得到精确的减法结果 + //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的减法结果。 + //调用:$h.Sub(arg1,arg2) + //返回值:arg1减去arg2的精确结果 + Sub: function(arg1, arg2) { + arg1 = parseFloat(arg1); + arg2 = parseFloat(arg2); + var r1, r2, m, n; + try { + r1 = arg1.toString().split(".")[1].length + } catch (e) { + r1 = 0 + } + try { + r2 = arg2.toString().split(".")[1].length + } catch (e) { + r2 = 0 + } + m = Math.pow(10, Math.max(r1, r2)); + //动态控制精度长度 + n = (r1 >= r2) ? r1 : r2; + return ((this.Mul(arg1, m) - this.Mul(arg2, m)) / m).toFixed(n); + }, + //乘法函数,用来得到精确的乘法结果 + //说明:javascript的乘法结果会有误差,在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。 + //调用:$h.Mul(arg1,arg2) + //返回值:arg1乘以arg2的精确结果 + Mul: function(arg1, arg2) { + arg1 = parseFloat(arg1); + arg2 = parseFloat(arg2); + var m = 0, + s1 = arg1.toString(), + s2 = arg2.toString(); + try { + m += s1.split(".")[1].length + } catch (e) {} + try { + m += s2.split(".")[1].length + } catch (e) {} + return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m); + }, } const formatNumber = n => { - n = n.toString() - return n[1] ? n : '0' + n + n = n.toString() + return n[1] ? n : '0' + n } /** @@ -78,295 +108,336 @@ const formatNumber = n => { * @param string p 单个分隔符 默认为:= * @return object * -*/ -const getUrlParams = (param,k,p) => { - if (typeof param!='string') return {}; - k = k ? k : '&';//整体参数分隔符 - p = p ? p : '=';//单个参数分隔符 - var value = {}; - if (param.indexOf(k) !== -1) { - param = param.split(k); - for (var val in param) { - if (param[val].indexOf(p) !== -1) { - var item = param[val].split(p); - value[item[0]] = item[1]; - } - } - } else if (param.indexOf(p) !== -1){ - var item = param.split(p); - value[item[0]] = item[1]; - }else{ - return param; - } - return value; + */ +const getUrlParams = (param, k, p) => { + if (typeof param != 'string') return {}; + k = k ? k : '&'; //整体参数分隔符 + p = p ? p : '='; //单个参数分隔符 + var value = {}; + if (param.indexOf(k) !== -1) { + param = param.split(k); + for (var val in param) { + if (param[val].indexOf(p) !== -1) { + var item = param[val].split(p); + value[item[0]] = item[1]; + } + } + } else if (param.indexOf(p) !== -1) { + var item = param.split(p); + value[item[0]] = item[1]; + } else { + return param; + } + return value; } -const wxgetUserInfo = function() -{ - return new Promise((resolve, reject) =>{ - wx.getUserInfo({ - lang: 'zh_CN', - success(res) { - resolve(res); - }, - fail(res){ - reject(res); - } - }) - }); +const wxgetUserInfo = function() { + return new Promise((resolve, reject) => { + wx.getUserInfo({ + lang: 'zh_CN', + success(res) { + resolve(res); + }, + fail(res) { + reject(res); + } + }) + }); } -const checkLogin = function (token, expiresTime, isLog) -{ - if (getApp()){ - token = getApp().globalData.token; - expiresTime = getApp().globalData.expiresTime; - isLog = getApp().globalData.isLog; - } - let res = token ? true : false; - let res1 = isLog; - let res2 = res && res1; - if (res2){ - let newTime=Math.round(new Date() / 1000); - if (expiresTime < newTime) return false; - } - return res2; +/** + * 新版小程序获取用户信息 2021 4.13微信小程序开始正式启用 + */ +const getUserProfile = function(code) { + return new Promise((resolve, reject) => { + wx.getUserProfile({ + lang: 'zh_CN', + desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写 + success(user) { + resolve(res); + }, + fail(res) { + reject(res); + } + }) + }) } -const logout = function() -{ - getApp().globalData.token = ''; - getApp().globalData.isLog = false; +const checkLogin = function(token, expiresTime, isLog) { + if (getApp()) { + token = getApp().globalData.token; + expiresTime = getApp().globalData.expiresTime; + isLog = getApp().globalData.isLog; + } + let res = token ? true : false; + let res1 = isLog; + let res2 = res && res1; + if (res2) { + let newTime = Math.round(new Date() / 1000); + if (expiresTime < newTime) return false; + } + return res2; } -const chekWxLogin = function() -{ - return new Promise((resolve, reject)=>{ - if (checkLogin()) - return resolve({ userinfo: getApp().globalData.userInfo, isLogin: true }); - wx.getSetting({ - success(res) { - if (!res.authSetting['scope.userInfo']) { - return reject({authSetting:false}); - } else { - wx.getStorage({ - key: 'cache_key', - success(res){ - wxgetUserInfo().then(userInfo => { - userInfo.cache_key = res.data; - return resolve({ userInfo: userInfo, isLogin: false }); - }).catch(res => { - return reject(res); - }); - }, - fail(){ - getCodeLogin((code) => { - wxgetUserInfo().then(userInfo => { - userInfo.code = code; - return resolve({ userInfo: userInfo, isLogin: false }); - }).catch(res => { - return reject(res); - }) - }); - } - }) - - } - }, - fail(res) { - return reject(res); - } - }) - }) +const logout = function() { + getApp().globalData.token = ''; + getApp().globalData.isLog = false; +} + +const chekWxLogin = function() { + return new Promise((resolve, reject) => { + if (checkLogin()) + return resolve({ + userinfo: getApp().globalData.userInfo, + isLogin: true + }); + wx.getSetting({ + success(res) { + if (!res.authSetting['scope.userInfo']) { + return reject({ + authSetting: false + }); + } else { + wx.getStorage({ + key: 'cache_key', + success(res) { + wxgetUserInfo().then(userInfo => { + userInfo.cache_key = res.data; + return resolve({ + userInfo: userInfo, + isLogin: false + }); + }).catch(res => { + return reject(res); + }); + }, + fail() { + getCodeLogin((code) => { + wxgetUserInfo().then(userInfo => { + userInfo.code = code; + return resolve({ + userInfo: userInfo, + isLogin: false + }); + }).catch(res => { + return reject(res); + }) + }); + } + }) + + } + }, + fail(res) { + return reject(res); + } + }) + }) } /** * * 授权过后自动登录 -*/ -const autoLogin = function() -{ - return new Promise((resolve, reject) => { - wx.getStorage({ - key: 'cache_key', - success(res) { - wxgetUserInfo().then(userInfo => { - userInfo.cache_key = res.data; - return resolve(userInfo); - }).catch(res => { - return reject(res); - }) - }, - fail(){ - getCodeLogin((code) => { - wxgetUserInfo().then(userInfo => { - userInfo.code = code; - return resolve(userInfo); - }).catch(res => { - return reject(res); - }) - }); - } - }); - }) + */ +const autoLogin = function() { + return new Promise((resolve, reject) => { + wx.getStorage({ + key: 'cache_key', + success(res) { + wxgetUserInfo().then(userInfo => { + userInfo.cache_key = res.data; + return resolve(userInfo); + }).catch(res => { + return reject(res); + }) + }, + fail() { + getCodeLogin((code) => { + wxgetUserInfo().then(userInfo => { + userInfo.code = code; + return resolve(userInfo); + }).catch(res => { + return reject(res); + }) + }); + } + }); + }) } -const getCodeLogin = function(successFn) -{ - wx.login({ - success(res){ - successFn(res); - } - }) +const getCodeLogin = function(successFn) { + wx.login({ + success(res) { + successFn(res); + } + }) } /* -* 合并数组 -*/ -const SplitArray= function (list, sp) { - if (typeof list != 'object') return []; - if (sp === undefined) sp = []; - for (var i = 0; i < list.length; i++) { - sp.push(list[i]); - } - return sp; + * 合并数组 + */ +const SplitArray = function(list, sp) { + if (typeof list != 'object') return []; + if (sp === undefined) sp = []; + for (var i = 0; i < list.length; i++) { + sp.push(list[i]); + } + return sp; } - /** - * opt object | string - * to_url object | string - * 例: - * this.Tips('/pages/test/test'); 跳转不提示 - * this.Tips({title:'提示'},'/pages/test/test'); 提示并跳转 - * this.Tips({title:'提示'},{tab:1,url:'/pages/index/index'}); 提示并跳转值table上 - * tab=1 一定时间后跳转至 table上 - * tab=2 一定时间后跳转至非 table上 - * tab=3 一定时间后返回上页面 - * tab=4 关闭所有页面跳转至非table上 - * tab=5 关闭当前页面跳转至table上 - */ -const Tips= function (opt, to_url) { - if (typeof opt == 'string') { - to_url = opt; - opt = {}; - } - var title = opt.title || '', icon = opt.icon || 'none', endtime = opt.endtime || 2000; - if (title) wx.showToast({ title: title, icon: icon, duration: endtime }) - if (to_url != undefined) { - if (typeof to_url == 'object') { - var tab = to_url.tab || 1, url = to_url.url || ''; - switch (tab) { - case 1: - //一定时间后跳转至 table - setTimeout(function () { - wx.switchTab({ - url: url - }) - }, endtime); - break; - case 2: - //跳转至非table页面 - setTimeout(function () { - wx.navigateTo({ - url: url, - }) - }, endtime); - break; - case 3: - //返回上页面 - setTimeout(function () { - wx.navigateBack({ - delta: parseInt(url), - }) - }, endtime); - break; - case 4: - //关闭当前所有页面跳转至非table页面 - setTimeout(function () { - wx.reLaunch({ - url: url, - }) - }, endtime); - break; - case 5: - //关闭当前页面跳转至非table页面 - setTimeout(function () { - wx.redirectTo({ - url: url, - }) - }, endtime); - break; - } +/** + * opt object | string + * to_url object | string + * 例: + * this.Tips('/pages/test/test'); 跳转不提示 + * this.Tips({title:'提示'},'/pages/test/test'); 提示并跳转 + * this.Tips({title:'提示'},{tab:1,url:'/pages/index/index'}); 提示并跳转值table上 + * tab=1 一定时间后跳转至 table上 + * tab=2 一定时间后跳转至非 table上 + * tab=3 一定时间后返回上页面 + * tab=4 关闭所有页面跳转至非table上 + * tab=5 关闭当前页面跳转至table上 + */ +const Tips = function(opt, to_url) { + if (typeof opt == 'string') { + to_url = opt; + opt = {}; + } + var title = opt.title || '', + icon = opt.icon || 'none', + endtime = opt.endtime || 2000; + if (title) wx.showToast({ + title: title, + icon: icon, + duration: endtime + }) + if (to_url != undefined) { + if (typeof to_url == 'object') { + var tab = to_url.tab || 1, + url = to_url.url || ''; + switch (tab) { + case 1: + //一定时间后跳转至 table + setTimeout(function() { + wx.switchTab({ + url: url + }) + }, endtime); + break; + case 2: + //跳转至非table页面 + setTimeout(function() { + wx.navigateTo({ + url: url, + }) + }, endtime); + break; + case 3: + //返回上页面 + setTimeout(function() { + wx.navigateBack({ + delta: parseInt(url), + }) + }, endtime); + break; + case 4: + //关闭当前所有页面跳转至非table页面 + setTimeout(function() { + wx.reLaunch({ + url: url, + }) + }, endtime); + break; + case 5: + //关闭当前页面跳转至非table页面 + setTimeout(function() { + wx.redirectTo({ + url: url, + }) + }, endtime); + break; + } - }else if(typeof to_url == 'function'){ - setTimeout(function () { - to_url && to_url(); - }, endtime); - }else{ - //没有提示时跳转不延迟 - setTimeout(function () { - wx.navigateTo({ - url: to_url, - }) - }, title ? endtime : 0); - } - } + } else if (typeof to_url == 'function') { + setTimeout(function() { + to_url && to_url(); + }, endtime); + } else { + //没有提示时跳转不延迟 + setTimeout(function() { + wx.navigateTo({ + url: to_url, + }) + }, title ? endtime : 0); + } + } } /* -* 单图上传 -* @param object opt -* @param callable successCallback 成功执行方法 data -* @param callable errorCallback 失败执行方法 -*/ -const uploadImageOne=function (opt, successCallback, errorCallback) { - if (typeof opt === 'string') { - var url = opt; - opt = {}; - opt.url = url; - } - var count = opt.count || 1, sizeType = opt.sizeType || ['compressed'], sourceType = opt.sourceType || ['album', 'camera'], - is_load = opt.is_load || true, uploadUrl = opt.url || '', inputName = opt.name || 'pics'; - wx.chooseImage({ - count: count, //最多可以选择的图片总数 - sizeType: sizeType, // 可以指定是原图还是压缩图,默认二者都有 - sourceType: sourceType, // 可以指定来源是相册还是相机,默认二者都有 - success: function (res) { - //启动上传等待中... - wx.showLoading({ - title: '图片上传中', - }); - wx.uploadFile({ - url: getApp().globalData.url+'/api/'+uploadUrl, - filePath: res.tempFilePaths[0], - name: inputName, - formData: { - 'filename': inputName - }, - header: { - "Content-Type": "multipart/form-data", - [TOKENNAME]: 'Bearer '+getApp().globalData.token - }, - success: function (res) { - wx.hideLoading(); - if (res.statusCode == 403) { - Tips({ title: res.data }); - } else { - var data = res.data ? JSON.parse(res.data) : {}; - if (data.status == 200) { - successCallback && successCallback(data) - } else { - errorCallback && errorCallback(data); - Tips({ title: data.msg }); - } - } - }, fail: function (res) { - wx.hideLoading(); - Tips({ title: '上传图片失败' }); - } - }) - } - }) + * 单图上传 + * @param object opt + * @param callable successCallback 成功执行方法 data + * @param callable errorCallback 失败执行方法 + */ +const uploadImageOne = function(opt, successCallback, errorCallback) { + if (typeof opt === 'string') { + var url = opt; + opt = {}; + opt.url = url; + } + var count = opt.count || 1, + sizeType = opt.sizeType || ['compressed'], + sourceType = opt.sourceType || ['album', 'camera'], + is_load = opt.is_load || true, + uploadUrl = opt.url || '', + inputName = opt.name || 'pics'; + wx.chooseImage({ + count: count, //最多可以选择的图片总数 + sizeType: sizeType, // 可以指定是原图还是压缩图,默认二者都有 + sourceType: sourceType, // 可以指定来源是相册还是相机,默认二者都有 + success: function(res) { + //启动上传等待中... + wx.showLoading({ + title: '图片上传中', + }); + wx.uploadFile({ + url: getApp().globalData.url + '/api/' + uploadUrl, + filePath: res.tempFilePaths[0], + name: inputName, + formData: { + 'filename': inputName + }, + header: { + "Content-Type": "multipart/form-data", + [TOKENNAME]: 'Bearer ' + getApp().globalData.token + }, + success: function(res) { + wx.hideLoading(); + if (res.statusCode == 403) { + Tips({ + title: res.data + }); + } else { + var data = res.data ? JSON.parse(res.data) : {}; + if (data.status == 200) { + successCallback && successCallback(data) + } else { + errorCallback && errorCallback(data); + Tips({ + title: data.msg + }); + } + } + }, + fail: function(res) { + wx.hideLoading(); + Tips({ + title: '上传图片失败' + }); + } + }) + } + }) } /** @@ -376,51 +447,51 @@ const uploadImageOne=function (opt, successCallback, errorCallback) { * @param string | int 值 * @return array * -*/ -const ArrayRemove= (array,index,value) =>{ - const valueArray=[]; - if (array instanceof Array){ - for (let i = 0; i < array.length;i++){ - if (typeof index == 'number' && array[index] != i){ - valueArray.push(array[i]); - } else if (typeof index == 'string' && array[i][index] != value){ - valueArray.push(array[i]); - } - } - } - return valueArray; -} - /** - * 生成海报获取文字 - * @param string text 为传入的文本 - * @param int num 为单行显示的字节长度 - * @return array */ -const textByteLength = (text, num) =>{ - let strLength = 0; - let rows = 1; - let str = 0; - let arr = []; - for (let j = 0; j < text.length; j++) { - if (text.charCodeAt(j) > 255) { - strLength += 2; - if (strLength > rows * num) { - strLength++; - arr.push(text.slice(str, j)); - str = j; - rows++; - } - } else { - strLength++; - if (strLength > rows * num) { - arr.push(text.slice(str, j)); - str = j; - rows++; - } - } - } - arr.push(text.slice(str, text.length)); - return [strLength, arr, rows] // [处理文字的总字节长度,每行显示内容的数组,行数] +const ArrayRemove = (array, index, value) => { + const valueArray = []; + if (array instanceof Array) { + for (let i = 0; i < array.length; i++) { + if (typeof index == 'number' && array[index] != i) { + valueArray.push(array[i]); + } else if (typeof index == 'string' && array[i][index] != value) { + valueArray.push(array[i]); + } + } + } + return valueArray; +} +/** + * 生成海报获取文字 + * @param string text 为传入的文本 + * @param int num 为单行显示的字节长度 + * @return array + */ +const textByteLength = (text, num) => { + let strLength = 0; + let rows = 1; + let str = 0; + let arr = []; + for (let j = 0; j < text.length; j++) { + if (text.charCodeAt(j) > 255) { + strLength += 2; + if (strLength > rows * num) { + strLength++; + arr.push(text.slice(str, j)); + str = j; + rows++; + } + } else { + strLength++; + if (strLength > rows * num) { + arr.push(text.slice(str, j)); + str = j; + rows++; + } + } + } + arr.push(text.slice(str, text.length)); + return [strLength, arr, rows] // [处理文字的总字节长度,每行显示内容的数组,行数] } /** @@ -431,67 +502,73 @@ const textByteLength = (text, num) =>{ * @param function successFn 回调函数 * * -*/ -const PosterCanvas = (arr2, store_name, price,successFn) =>{ - wx.showLoading({ title: '海报生成中', mask: true }); - const ctx = wx.createCanvasContext('myCanvas'); - ctx.clearRect(0, 0, 0, 0); - /** - * 只能获取合法域名下的图片信息,本地调试无法获取 - * - */ - wx.getImageInfo({ - src: arr2[0], - success: function (res) { - const WIDTH = res.width; - const HEIGHT = res.height; - ctx.drawImage(arr2[0], 0, 0, WIDTH, HEIGHT); - ctx.drawImage(arr2[1], 0, 0, WIDTH, WIDTH); - ctx.save(); - let r = 90; - let d = r * 2; - let cx = 40; - let cy = 990; - ctx.arc(cx + r, cy + r, r, 0, 2 * Math.PI); - ctx.clip(); - ctx.drawImage(arr2[2], cx, cy, d, d); - ctx.restore(); - const CONTENT_ROW_LENGTH = 40; - let [contentLeng, contentArray, contentRows] = textByteLength(store_name, CONTENT_ROW_LENGTH); - if (contentRows > 2) { - contentRows =2; - let textArray=contentArray.slice(0,2); - textArray[textArray.length-1]+='……'; - contentArray = textArray; - } - ctx.setTextAlign('center'); - ctx.setFontSize(32); - let contentHh = 32 * 1.3; - for (let m = 0; m < contentArray.length; m++) { - ctx.fillText(contentArray[m], WIDTH / 2, 820 + contentHh * m); - } - ctx.setTextAlign('center') - ctx.setFontSize(48); - ctx.setFillStyle('red'); - ctx.fillText('¥' + price, WIDTH / 2, 860 + contentHh); - ctx.draw(true, function () { - wx.canvasToTempFilePath({ - canvasId: 'myCanvas', - fileType: 'png', - destWidth: WIDTH, - destHeight: HEIGHT, - success: function (res) { - wx.hideLoading(); - successFn && successFn(res.tempFilePath); - } - }) - }); - }, - fail:function(){ - wx.hideLoading(); - Tips({title:'无法获取图片信息'}); - } - }) + */ +const PosterCanvas = (arr2, store_name, price, successFn) => { + wx.showLoading({ + title: '海报生成中', + mask: true + }); + const ctx = wx.createCanvasContext('myCanvas'); + ctx.clearRect(0, 0, 0, 0); + /** + * 只能获取合法域名下的图片信息,本地调试无法获取 + * + */ + wx.getImageInfo({ + src: arr2[0], + success: function(res) { + const WIDTH = res.width; + const HEIGHT = res.height; + ctx.drawImage(arr2[0], 0, 0, WIDTH, HEIGHT); + ctx.drawImage(arr2[1], 0, 0, WIDTH, WIDTH); + ctx.save(); + let r = 90; + let d = r * 2; + let cx = 40; + let cy = 990; + ctx.arc(cx + r, cy + r, r, 0, 2 * Math.PI); + ctx.clip(); + ctx.drawImage(arr2[2], cx, cy, d, d); + ctx.restore(); + const CONTENT_ROW_LENGTH = 40; + let [contentLeng, contentArray, contentRows] = textByteLength(store_name, + CONTENT_ROW_LENGTH); + if (contentRows > 2) { + contentRows = 2; + let textArray = contentArray.slice(0, 2); + textArray[textArray.length - 1] += '……'; + contentArray = textArray; + } + ctx.setTextAlign('center'); + ctx.setFontSize(32); + let contentHh = 32 * 1.3; + for (let m = 0; m < contentArray.length; m++) { + ctx.fillText(contentArray[m], WIDTH / 2, 820 + contentHh * m); + } + ctx.setTextAlign('center') + ctx.setFontSize(48); + ctx.setFillStyle('red'); + ctx.fillText('¥' + price, WIDTH / 2, 860 + contentHh); + ctx.draw(true, function() { + wx.canvasToTempFilePath({ + canvasId: 'myCanvas', + fileType: 'png', + destWidth: WIDTH, + destHeight: HEIGHT, + success: function(res) { + wx.hideLoading(); + successFn && successFn(res.tempFilePath); + } + }) + }); + }, + fail: function() { + wx.hideLoading(); + Tips({ + title: '无法获取图片信息' + }); + } + }) } /** @@ -501,45 +578,46 @@ const PosterCanvas = (arr2, store_name, price,successFn) =>{ * @param object that 当前this * @param string name 变动字段名称 * */ -const AnimationNumber = (BaseNumber,ChangeNumber,that,name) => { - var difference = $h.Sub(ChangeNumber,BaseNumber) //与原数字的差 - var absDifferent = Math.abs(difference) //差取绝对值 - var changeTimes = absDifferent < 6 ? absDifferent : 6 //最多变化6次 - var changeUnit = absDifferent < 6 ? 1 : Math.floor(difference/6); - // 依次变化 - for (var i = 0; i < changeTimes; i += 1) { - // 使用闭包传入i值,用来判断是不是最后一次变化 - (function (i) { - setTimeout(() => { - that.setData({ - [name]: $h.Add(BaseNumber,changeUnit) - }) - // 差值除以变化次数时,并不都是整除的,所以最后一步要精确设置新数字 - if (i == changeTimes - 1) { - that.setData({ - [name]: $h.Add(BaseNumber, difference) - }) - } - }, 100 * (i + 1)) - })(i) - } +const AnimationNumber = (BaseNumber, ChangeNumber, that, name) => { + var difference = $h.Sub(ChangeNumber, BaseNumber) //与原数字的差 + var absDifferent = Math.abs(difference) //差取绝对值 + var changeTimes = absDifferent < 6 ? absDifferent : 6 //最多变化6次 + var changeUnit = absDifferent < 6 ? 1 : Math.floor(difference / 6); + // 依次变化 + for (var i = 0; i < changeTimes; i += 1) { + // 使用闭包传入i值,用来判断是不是最后一次变化 + (function(i) { + setTimeout(() => { + that.setData({ + [name]: $h.Add(BaseNumber, changeUnit) + }) + // 差值除以变化次数时,并不都是整除的,所以最后一步要精确设置新数字 + if (i == changeTimes - 1) { + that.setData({ + [name]: $h.Add(BaseNumber, difference) + }) + } + }, 100 * (i + 1)) + })(i) + } } module.exports = { - formatTime: formatTime, - $h:$h, - Tips: Tips, - uploadImageOne: uploadImageOne, - SplitArray: SplitArray, - ArrayRemove: ArrayRemove, - PosterCanvas: PosterCanvas, - AnimationNumber: AnimationNumber, - getUrlParams: getUrlParams, - chekWxLogin: chekWxLogin, - getCodeLogin: getCodeLogin, - checkLogin: checkLogin, - wxgetUserInfo: wxgetUserInfo, - autoLogin: autoLogin, - logout: logout -} + formatTime: formatTime, + $h: $h, + Tips: Tips, + uploadImageOne: uploadImageOne, + SplitArray: SplitArray, + ArrayRemove: ArrayRemove, + PosterCanvas: PosterCanvas, + AnimationNumber: AnimationNumber, + getUrlParams: getUrlParams, + chekWxLogin: chekWxLogin, + getCodeLogin: getCodeLogin, + checkLogin: checkLogin, + wxgetUserInfo: wxgetUserInfo, + autoLogin: autoLogin, + logout: logout, + getUserProfile: getUserProfile +}