Util工具類可以提高開發效率,比如POST、GET請求,圖片上傳,數組操作等等,將常用的方法進行封裝,方便使用。
下面是我在做項目的時候編寫整理的一部分。
先上代碼
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()
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 (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
}
/**
* 處理服務器掃碼帶進來的參數
* @param string param 掃碼攜帶參數
* @param string k 整體分割符 默認為:&
* @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 {
var item = param.split(p);
value[item[0]] = item[1];
}
return value;
}
/*
* post網絡請求
* @param string | object 請求地址
* @param object data POST請求數組
* @param callable successCallback 成功執行方法
* @param callable errorCallback 失敗執行方法
*/
const basePost = function (url, data, successCallback, errorCallback, header) {
console.log('請求url:' + url);
wx.showLoading({
title: "正在加載中...",
})
wx.request({
url: url,
data: data,
dataType: 'json',
method: 'POST',
header: {
"Content-Type": "application/json"
},
success: function (res) {
wx.hideLoading();
console.log('響應:', res.data);
try {
if (res.data.code == 200) {
successCallback && successCallback(res.data);
} else {
if (res.data.code == 402) getApp().globalData.token = '', getApp().globalData.isLog = false;
//返回狀態為401時,用戶被禁止訪問 關閉當前所有頁面跳轉至用戶禁止登錄頁面
if (res.data.code == 401) return Tips({
title: res.data.msg
});
errorCallback && errorCallback(res.data);
}
} catch (e) {
console.log(e);
}
},
fail: function (res) {
errorCallback && errorCallback(res);
},
complete: function (res) {
}
});
}
/*
* get網絡請求
* @param string | object 請求地址
* @param callable successCallback 成功執行方法
* @param callable errorCallback 失敗執行方法
* @param boolean isMsg 是否自動提示錯誤 默認提示
*/
const baseGet = function (url, successCallback, errorCallback, isMsg, header) {
console.log('請求url:' + url);
wx.showLoading({
title: "正在加載中...",
})
wx.request({
url: url,
dataType: 'json',
method: 'GET',
header: header,
success: function (res) {
wx.hideLoading();
console.log('響應:', res.data);
try {
if (res.data.code == 200) {
successCallback && successCallback(res.data);
} else {
if (res.data.code == 402) getApp().globalData.token = '', getApp().globalData.isLog = false;
//返回狀態為401時,用戶被禁止訪問 關閉當前所有頁面跳轉至用戶禁止登錄頁面
if (res.data.code == 401) return Tips({
title: res.data.msg
});
errorCallback && errorCallback(res.data);
isMsg || Tips({
title: res.data.msg
});
}
} catch (e) {
console.log(e);
}
},
fail: function (res) {
console.log('submit fail');
},
complete: function (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;
}
/**
* 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);
}
}
}
/*
* 單圖上傳
* @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: uploadUrl,
filePath: res.tempFilePaths[0],
name: inputName,
formData: {
'filename': inputName
},
header: {
"Content-Type": "multipart/form-data",
token: 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.code == 200) {
successCallback && successCallback(data)
} else {
errorCallback && errorCallback(data);
Tips({
title: data.msg
});
}
}
},
fail: function (res) {
wx.hideLoading();
Tips({
title: '上傳圖片失敗'
});
}
})
}
})
}
/**
* 移除數組中的某個數組並組成新的數組返回
* @param array array 需要移除的數組
* @param int index 需要移除的數組的鍵值
* @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] // [處理文字的總字節長度,每行顯示內容的數組,行數]
}
/**
* 獲取分享海報
* @param array arr2 海報素材
* @param string store_name 素材文字
* @param string price 價格
* @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) {
console.log(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);
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: '無法獲取圖片信息'
});
}
})
}
/**
* 數字變動動畫效果
* @param float BaseNumber 原數字
* @param float ChangeNumber 變動后的數字
* @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)
}
}
/**
* 處理富文本里的圖片寬度自適應
* 1.去掉img標簽里的style、width、height屬性
* 2.img標簽添加style屬性:max-width:100%;height:auto
* 3.修改所有style里的width屬性為max-width:100%
* 4.去掉<br/>標簽
* @param html
* @returns {void|string|*}
*/
function formatRichText(html) {
let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
return match;
});
newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
return match;
});
newContent = newContent.replace(/<br[^>]*\/>/gi, '');
newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
return newContent;
}
//將秒數轉換為時分秒格式
function formatSeconds(value) {
var theTime = parseInt(value); // 秒
var middle = 0; // 分
var hour = 0; // 小時
if (theTime > 60) {
middle = parseInt(theTime / 60);
theTime = parseInt(theTime % 60);
if (middle > 60) {
hour = parseInt(middle / 60);
middle = parseInt(middle % 60);
}
}
var result = "" + parseInt(theTime) + "秒";
if (middle > 0) {
result = "" + parseInt(middle) + "分" + result;
}
if (hour > 0) {
result = "" + parseInt(hour) + "小時" + result;
}
return result;
}
module.exports = {
formatTime: formatTime,
$h: $h,
Tips: Tips,
uploadImageOne: uploadImageOne,
basePost: basePost,
SplitArray: SplitArray,
baseGet: baseGet,
ArrayRemove: ArrayRemove,
PosterCanvas: PosterCanvas,
AnimationNumber: AnimationNumber,
getUrlParams: getUrlParams,
formatRichText: formatRichText,
formatSeconds: formatSeconds
}
使用
1、在utils/util.js文件中添加上述代碼
2、在需要使用工具類的js文件中添加
var util = require('../../utils/util.js');
3、util.XXX來調用
util.baseGet(app.globalData.apiurl + "api/XXX/XXX", prams,
function (res) {
console.log(res.Result)
that.setData({
})
},
function (err) {
}
)
到此就可以愉快的使用了
希望能對你有所幫助