当前位置:网站首页>Applet utils
Applet utils
2022-07-27 02:43:00 【kilito_ 01】
const utils = {
// domain name
domain: 'http://',
// Address of the interface
interfaceUrl: function() {
return utils.domain
},
toast: function(text, duration, success) {
uni.showToast({
title: text || " Error ~",
icon: success || 'none',
duration: duration || 2000
})
},
modal: function(title, content, showCancel = false, callback, confirmColor, confirmText, cancelColor,
cancelText) {
uni.showModal({
title: title || ' Tips ',
content: content,
showCancel: showCancel,
cancelColor: cancelColor || "#555",
confirmColor: confirmColor || "#e41f19",
confirmText: confirmText || " determine ",
cancelText: cancelText || " Cancel ",
success(res) {
if (res.confirm) {
callback && callback(true)
} else {
callback && callback(false)
}
}
})
},
isAndroid: function() {
const res = uni.getSystemInfoSync();
return res.platform.toLocaleLowerCase() == "android"
},
isIphoneX: function() {
const res = uni.getSystemInfoSync();
let iphonex = false;
let models = ['iphonex', 'iphonexr', 'iphonexsmax', 'iphone11', 'iphone11pro', 'iphone11promax']
const model = res.model.replace(/\s/g, "").toLowerCase()
if (models.includes(model)) {
iphonex = true;
}
return iphonex;
},
constNum: function() {
let time = 0;
// #ifdef APP-PLUS
time = this.isAndroid() ? 300 : 0;
// #endif
return time
},
delayed: null,
/**
* Request data processing
* @param string url Request address
* @param {
*} postData Request parameters
* @param string method Request mode
* GET or POST
* @param string contentType data format
* 'application/x-www-form-urlencoded'
* 'application/json'
* @param bool isDelay Whether to delay the display loading
* @param bool hideLoading Is it hidden loading
* true: hide
* false: Show
*/
request: function(url, postData = {
}, method = "GET", contentType = "application/x-www-form-urlencoded",
isDelay, hideLoading) {
// Interface request
let loadding = false;
utils.delayed && uni.hideLoading();
clearTimeout(utils.delayed);
utils.delayed = null;
if (!hideLoading) {
utils.delayed = setTimeout(() => { uni.showLoading({ mask: true, title: ' Please wait a moment ...', success(res) { loadding = true } }) }, isDelay ? 1000 : 0) } return new Promise((resolve, reject) => { uni.request({ url: utils.interfaceUrl() + url, data: postData, header: { 'content-type': contentType, // This request header needs to be aligned with the backend Need to change 'Authorization': utils.getToken() }, method: method, //'GET','POST' dataType: 'json', success: (res) => { if (loadding && !hideLoading) { uni.hideLoading() } if (res.statusCode === 200) { // if (res.data.errno === 401) { // utils.modal(' reminder ', ' You haven't signed in yet , Whether to log in ', true, (confirm) => { // if (confirm) { // uni.redirectTo({ // url: '/pages/login/login', // }) // } else { // uni.navigateBack({ // delta: 1, // fail: (res) => { // uni.switchTab({ // url: '/pages/index/index', // }) // } // }) // } // }) // } else if (res.data.errno === 500) { // utils.toast(res.data.msg) // } else if (res.data.errno === 404) { // utils.toast(res.data.msg) // } // else { resolve(res.data); // } } else { reject(res.data.msg); } }, fail: (res) => { utils.toast(" The network suck up , Please try again later ~") reject(res) }, complete: function(res) { clearTimeout(utils.delayed) utils.delayed = null; if (res.statusCode === 200) { // if (res.data.errno === 0 || res.data.errno === 401) { uni.hideLoading() // } else { // utils.toast(res.data.msg) // } } else { utils.toast(' The server is on the blink ~') } } }) }) }, /** * Upload files * @param string url Request address * @param string src File path */ uploadFile: function(url, src) { uni.showLoading({ title: ' Please wait a moment ...' }) return new Promise((resolve, reject) => { const uploadTask = uni.uploadFile({ url: utils.interfaceUrl() + url, filePath: src, name: 'file', header: { 'content-type': 'multipart/form-data', 'Authorization': utils.getToken() }, success: function(res) { uni.hideLoading() let data = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}") if (data.errno == 0) { // Return image address resolve(data) } else { that.toast(res.msg); } }, fail: function(res) { utils.toast(" The network suck up , Please try again later ~") reject(res) } }) }) }, tuiJsonp: function(url, callback, callbackname) { // #ifdef H5 window[callbackname] = callback; let tuiScript = document.createElement("script"); tuiScript.src = url; tuiScript.type = "text/javascript"; document.head.appendChild(tuiScript); document.head.removeChild(tuiScript); // #endif }, set: function(key, value) { uni.setStorageSync(key, value) }, get: function(key) { return uni.getStorageSync(key) }, // Set up token setToken: function(mobile, token) { uni.setStorageSync("Authorization", token) }, // obtain token getToken: function() { return uni.getStorageSync("Authorization") }, go(url, type = '') { if (url[0] !== '/') { url = '/' + url; } switch (type) { case '': uni.navigateTo({ url: url }); break; case 'redirect': uni.redirectTo({ url: url }); break; case 'reLaunch': uni.reLaunch({ url: url }); default: uni.navigateTo({ url: url }); break; } }, // Return to upper level goBack:function(){ uni.navigateBack({ delta: 1 }); }, // The safe distance at the bottom getScreenPaddingBottom:function(){ // This value is px var obj = uni.getSystemInfoSync(); var paddingBottom = obj.screenHeight - obj.safeArea.bottom; return paddingBottom }, // Get the width of the capsule from the left getMenuButton(){ let menuButtonObject = uni.getMenuButtonBoundingClientRect(); // because navbar On the left side of the road is 20px Of padding value So you have to lose 20 let navObjWid = menuButtonObject.left - 20 return navObjWid }, // Go to space trim: function(value) { return value.replace(/(^\s*)|(\s*$)/g, ""); }, // Content substitution replaceAll: function(text, repstr, newstr) { return text.replace(new RegExp(repstr, "gm"), newstr); }, // Format the phone number formatNumber: function(num) { return num.length === 11 ? num.replace(/^(\d{
3})\d{
4}(\d{
4})$/, '$1****$2') : num; }, // Amount format rmoney: function(money) { return parseFloat(money).toFixed(2).toString().split('').reverse().join('').replace(/(\d{
3})/g, '$1,') .replace( /\,$/, '').split('').reverse().join(''); }, // Time format output , Such as 11:03 25:19 Every time 1s Will be called once dateformat: function(micro_second) { // Total seconds var second = Math.floor(micro_second / 1000); // Days var day = Math.floor(second / 3600 / 24); // Hours var hr = Math.floor(second / 3600 % 24); // minute var min = Math.floor(second / 60 % 60); // second var sec = Math.floor(second % 60); return { day, hr: hr < 10 ? '0' + hr : hr, min: min < 10 ? '0' + min : min, sec: sec < 10 ? '0' + sec : sec, second: second } }, // Date formatting formatDate: function(formatStr, fdate) { if (fdate) { if (~fdate.indexOf('.')) {
fdate = fdate.substring(0, fdate.indexOf('.'));
}
fdate = fdate.toString().replace('T', ' ').replace(/\-/g, '/');
var fTime, fStr = 'ymdhis';
if (!formatStr)
formatStr = "y-m-d h:i:s";
if (fdate)
fTime = new Date(fdate);
else
fTime = new Date();
var month = fTime.getMonth() + 1;
var day = fTime.getDate();
var hours = fTime.getHours();
var minu = fTime.getMinutes();
var second = fTime.getSeconds();
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
hours = hours < 10 ? ('0' + hours) : hours;
minu = minu < 10 ? '0' + minu : minu;
second = second < 10 ? '0' + second : second;
var formatArr = [
fTime.getFullYear().toString(),
month.toString(),
day.toString(),
hours.toString(),
minu.toString(),
second.toString()
]
for (var i = 0; i < formatArr.length; i++) {
formatStr = formatStr.replace(fStr.charAt(i), formatArr[i]);
}
return formatStr;
} else {
return "";
}
},
getDistance: function(lat1, lng1, lat2, lng2) {
function Rad(d) {
return d * Math.PI / 180.0;
}
if (!lat1 || !lng1) {
return '';
}
// lat1 User latitude
// lng1 Longitude of user
// lat2 The latitude of business
// lng2 Longitude of the merchant
let radLat1 = Rad(lat1);
let radLat2 = Rad(lat2);
let a = radLat1 - radLat2;
let b = Rad(lng1) - Rad(lng2);
let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) *
Math.pow(
Math.sin(b / 2), 2)));
s = s * 6378.137;
s = Math.round(s * 10000) / 10000;
s = '( From you ' + s.toFixed(2) + ' km )' // Keep two decimal places
return s
},
isMobile: function(mobile) {
if (!mobile) {
utils.toast(' Please enter your mobile number ');
return false
}
if (!mobile.match(/^1[3-9][0-9]\d{
8}$/)) {
utils.toast(' The cell phone number is incorrect ');
return false
}
return true
},
rgbToHex: function(r, g, b) {
return "#" + utils.toHex(r) + utils.toHex(g) + utils.toHex(b)
},
toHex: function(n) {
n = parseInt(n, 10);
if (isNaN(n)) return "00";
n = Math.max(0, Math.min(n, 255));
return "0123456789ABCDEF".charAt((n - n % 16) / 16) + "0123456789ABCDEF".charAt(n % 16); }, hexToRgb(hex) { let result = /^#?([a-f\d]{
2})([a-f\d]{
2})([a-f\d]{
2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; }, transDate: function(date, fmt) { if (!date) { return '--' } let _this = new Date(date * 1000) let o = { 'M+': _this.getMonth() + 1, 'd+': _this.getDate(), 'h+': _this.getHours(), 'm+': _this.getMinutes(), 's+': _this.getSeconds(), 'q+': Math.floor((_this.getMonth() + 3) / 3), 'S': _this.getMilliseconds() } if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (_this.getFullYear() + '').substr(4 - RegExp.$1.length))
}
for (let k in o) {
if (new RegExp('(' + k + ')').test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[ k]).length)))
}
}
return fmt
},
isNumber: function(val) {
let regPos = /^\d+(\.\d+)?$/; // Nonnegative floating point number
let regNeg =
/^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; // Negative floating point number
if (regPos.test(val) || regNeg.test(val)) {
return true;
} else {
return false;
}
},
// Determines if the string is empty
isEmpty: function(str) {
if (str === '' || str === undefined || str === null) {
return true;
} else {
return false;
}
},
expireTime: function(str) {
if (!str) {
return;
}
let NowTime = new Date().getTime();
//IOS The system directly uses new Date('2018-10-29 11:25:21'), stay IOS Cannot get the corresponding time object on .
let totalSecond = Date.parse(str.replace(/-/g, '/')) - NowTime || [];
if (totalSecond < 0) {
return;
}
return totalSecond / 1000
},
/**
* Unified order request
*/
payOrder: function(orderId) {
return new Promise(function(resolve, reject) {
utils.request('pay/prepay', {
orderId: orderId
}, 'POST').then((res) => {
if (res.errno === 0) {
let payParam = res.data;
uni.requestPayment({
'timeStamp': payParam.timeStamp,
'nonceStr': payParam.nonceStr,
'package': payParam.package,
'signType': payParam.signType,
'paySign': payParam.paySign,
'success': function(res) {
console.log(res)
resolve(res);
},
'fail': function(res) {
console.log(res)
reject(res);
},
'complete': function(res) {
console.log(res)
reject(res);
}
});
} else {
reject(res);
}
});
});
},
/**
* Call wechat login
*/
login: function() {
return new Promise(function(resolve, reject) {
uni.login({
success: function(res) {
if (res.code) {
resolve(res);
} else {
reject(res);
}
},
fail: function(err) {
reject(err);
}
});
});
}
}
module.exports = {
interfaceUrl: utils.interfaceUrl,
toast: utils.toast,
modal: utils.modal,
isAndroid: utils.isAndroid,
isIphoneX: utils.isIphoneX,
constNum: utils.constNum,
request: utils.request,
uploadFile: utils.uploadFile,
tuiJsonp: utils.tuiJsonp,
setToken: utils.setToken,
getToken: utils.getToken,
get:utils.get,
set:utils.set,
go:utils.go,
goBack:utils.goBack,
getScreenPaddingBottom:utils.getScreenPaddingBottom,
getMenuButton:utils.getMenuButton,
trim: utils.trim,
replaceAll: utils.replaceAll,
formatNumber: utils.formatNumber,
rmoney: utils.rmoney,
dateformat: utils.dateformat,
formatDate: utils.formatDate,
getDistance: utils.getDistance,
isMobile: utils.isMobile,
rgbToHex: utils.rgbToHex,
hexToRgb: utils.hexToRgb,
transDate: utils.transDate,
isNumber: utils.isNumber,
isEmpty: utils.isEmpty,
expireTime: utils.expireTime,
payOrder: utils.payOrder,
login: utils.login
}
边栏推荐
猜你喜欢

Hcip the next day

Record the nth SQL exception

JUC concurrent programming

【Redis】快速入门

Okaleido Tiger 7.27日登录Binance NFT,首轮已获不俗成绩

Smooth data migration from single table to sub table

LeetCode刷题——NO.238——除自身以外数组的乘积

Area optimization of digital chips: detailed explanation of question 1 in the digital direction of the third "Huawei Cup" graduate innovation core competition

OSPF summary (mind map)

Hcip day 4 OSPF routing protocol
随机推荐
Little sister's notes: how do I learn simple source code to expand my horizons
Prometheus operation and maintenance tool promtool (III) debug function
膜拜,阿里内部都在强推的321页互联网创业核心技术pdf,真的跪了
GoatGui邀你参加机器学习研讨班
JS 数组去重(含简单数组去重、对象数组去重)
[use SQLite3 library to realize student information management system in Visual Studio 2019]
Hcip day 6 OSPF static experiment
Tabbar of customized wechat applet on uni app
php+swoole
swiperjs自定义宽度
【Code】剑指offer 04二维数组中的查找
Hcip day 4 OSPF routing protocol
证券公司哪家手续费最低?手机上开户安全吗
hcip--ospf接口网络接口类型实验
项目时区问题解决
【力扣】1859.将句子排序
Greenplum【部署 08】数据库小版本升级流程及问题处理 Error: open-source-greenplum-db-6 conflicts with
最新多线程&高并发学习资料,面试心里有底气
OSPF summary (mind map)
LeetCode->二分查找打卡