当前位置:网站首页>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
}
边栏推荐
- Handsomeforum Learning Forum
- Three handshakes and four disconnects of TCP
- Prompt to leave the page
- 文章摘要智能提取【基于BERT技术】
- I wish you a happy Chinese Valentine's day and invite you to read the source code together
- C语言程序的编译上
- 进程的调度
- The XML format of labelimg annotation is converted to yolov5
- Smooth data migration from single table to sub table
- Qt中文乱码常量换行符终极解决方案
猜你喜欢

砺夏行动|源启数字化:既有模式,还是开源创新?

【Code】剑指offer 04二维数组中的查找

JUC concurrent programming

f8抓交通、f9抓兔子、f10turtle

Multipoint bidirectional republication and routing strategy topology experiment

Redis installation and operation (Linux)

从单表到分表实现数据平滑迁移

Hcip OSPF interface network interface type experiment

Hcip first day

GoatGui邀你参加机器学习研讨班
随机推荐
膜拜,阿里内部都在强推的321页互联网创业核心技术pdf,真的跪了
见证中国网安力量 “解码2022中国网安强星”即将启航
I was fired at the age of 30. I want to understand a few things
The XML format of labelimg annotation is converted to yolov5
[draw rectangular coordinate system in C language]
Hcip day 5 OSPF extended configuration experiment
Constant knowledge explanation of C language
文章主要内容提取软件[基于NLP技术]
消息队列学习 -- 概念
转:俞敏洪:阻碍你成长的,是你自己
平成千字文(へいせいせんじもん) (平成12年9月10日 石渡 明 作) 宇宙広遠 銀河永久 日月運行 不乱無休 地球公転 季節変移 黄道星座 太陽年周 故郷群島 南熱北冷 海洋温暖 気候順良 青空飛雲 諸野深緑 湖泉静息 谷川清流 春桜一面 新芽
Writing a pacesetter frequently -- yunxiaojing
FormData的使用
Hcip first day
中断、信号、系统调用
证券炒股开户需要现场开户吗网上开户安全吗
JMeter下载安装
[brother Yang takes you to play with the linear table (I) - sequence table]
项目时区问题解决
Prometheus 运维工具 Promtool (三) Debug 功能