当前位置:网站首页>Packaging method
Packaging method
2022-04-22 11:48:00 【Bruce Lee】
/**
- Remove the leading and trailing spaces in the string
- @param {string} str String parameters
/
const trim = (str) => {
if (str.length == 0) {
return “”;
} else {
return str.replace(/(^\s+)|(\s+$)/g, “”);
}
}
/* - Tips
- @param {string} title Prompt content
- @param {num} time Delay time
- @param {fun} successCallback Successful callback function
/
const alert = (title, successCallback, time) => {
uni.showToast({
icon: “success”,
title: title || “ success ”,
duration: time || 1000,
success: successCallback,
mask:true
})
}
/* - loading Tips
- @param {string} title Prompt content
- @param {num} time Delay time
- @param {Boolean} mask Display template
- @param {fun} successCallback Successful callback function
/
const loading = (title, mask, successCallback) => {
uni.showLoading({
icon: “loading”,
mask: mask || !0,
title: title || “ Loading …”,
success: successCallback
})
}
/* - hideloading Hidden prompt
- @param {num} time Delay time
/
const hideloading = (time) => {
// clearTimeout(e);
time = time || 0;
let e = setTimeout(function () {
uni.hideToast()
}, time)
}
/* - confirm Prompt box
- @param {string} title title
- @param {string} content Content
- @param {Boolean} showCancel Whether to display the exit button
- @param {fun} successCallback Successful return function
*/
const confirm = (title,content, showCancel,successCallback) => {
uni.showModal({
title: title || “ Tips ”,
content: content,
showCancel: showCancel || !1,
success: successCallback
})
}
/**
- gopage Page Jump (navigateTo: Keep the current page )
- @param {string} url Address
- @param {fun} successCallback Successful return function
/
const gopage = (url, successCallback) => {
uni.navigateTo({
url: url,
success: successCallback
})
}
/* - gotopage Page Jump (redirectTo, Close current page )
- @param {string} url Address
- @param {fun} successCallback Successful return function
/
const gotopage = (url, successCallback) => {
uni.redirectTo({
url: url,
success: successCallback
})
}
/* - gotarpage Page Jump (switchTab Jump to tarbar page )
- @param {string} url Address
- @param {fun} successCallback Successful return function
/
const gotarpage = (url, successCallback) => {
uni.switchTab({
url: url,
success: successCallback
})
}
/* - backpage Page back
- @param {num} delta Page layers
- @param {fun} successCallback Successful return function
/
const backpage = (delta) => {
uni.navigateBack({
delta: delta || 1,
})
}
/* - alertBack There is a pop-up box and the page returns
- @param {string} title Prompt title
- @param {num} time Time
- @param {string} url Page address
/
const alertBack = (title, url, time) => {
var time = time || 1000;
uni.showToast({
icon: “success”,
title: title || “ success ”,
duration: time,
success: () => {
setTimeout(() => {
if (url) {
uni.redirectTo({ url: url})
} else {
uni.navigateBack({ delta: 1 })
}
}, time)
}
})
}
/* - setCache Synchronize settings cache
- @param {string} key key value
- @param {string} value Content
/
const setCache = (key, value) => {
try {
uni.setStorageSync(key, value)
} catch (e) {
console.log(e)
}
}
/* - getCache Get cache synchronously
- @param {string} key key value
/
const getCache = (key) => {
try {
var value = uni.getStorageSync(key)
if (value) {
return value;
}
} catch (e) {
console.log(e)
// Do something when catch error
}
}
/* - removeCache Delete cache
- @param {string} key key value
- @param {fun} successCallback Successful return function
/
const removeCache = (key, successCallback) => {
uni.removeStorage({
key: key,
success: successCallback
})
}
/* - showToast Prompt function
- @param {string} title Prompt information
- @param {string} mask Mask
- @param {num} time Time
- getCurrentPages() Function to get an instance of the current page stack
*/
const showToast = (title, successCallback, time, mask) => {
uni.showToast({
icon: “none”,
title: title || “ success ”,
mask: mask || !0,
duration:time || 1500,
success: successCallback,
})
}
/**
- showerror Error message function
- @param {string} info Prompt information
- @param {string} url Address
- @param {num} time Time
- getCurrentPages() Function to get an instance of the current page stack
*/
const showerror = (info, url, time) => {
var index = getCurrentPages().length - 1;
var time = time || 1500;
if (url) {
getCurrentPages()[index].setData({
errorurl: url,
})
}
getCurrentPages()[index].setData({
errorflag: true,
errorinfo: info,
})
setTimeout(function () {
getCurrentPages()[index].setData({
errorflag: false,
errorinfo: ‘ Prompt information ’,
})
}, time)
}
/**
- Validation function
- @param {string} val Validation value
- @param {string} type Type of validation
/
const testing = (val, type) => {
var flag;
var rule;
if (val == undefined) {
showToast(“ Missing parameter ”)
return;
}
if (type == “mobile”) {
// Phone number
rule = /1[0-9]{10}KaTeX parse error: Expected 'EOF', got '}' at position 3: / }̲ else if (type …)[a-zA-Z0-9_\u4e00-\u9fa5]+KaTeX parse error: Expected 'EOF', got '}' at position 4: /; }̲ else if (type …/;
} else if (type == ‘password’) {
// password 4-20 character
rule = /^.{6,20}KaTeX parse error: Expected 'EOF', got '}' at position 4: /; }̲ else if (type …/;
} else if(type == ‘idCard’) {
rule = /2\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}KaTeX parse error: Undefined control sequence: \d at position 8: |^[1-9]\̲d̲{5}[1-9]\d{3}((…/;
} else if(type == ‘bankCode’){
rule =/^([1-9]{1})(\d{14}|\d{15}|\d{16}|\d{18})KaTeX parse error: Expected 'EOF', got '}' at position 3: / }̲else{ // Non empty verification 1…/;
}
rule.test(val) ? flag = true : flag = false;
return flag;
}
/* - Gets the length of the string
- @param {string} text character string
*/
const getstringwidth = (text) => {
var jmz = {};
jmz.GetLength = function (text) {
return text.replace(/[\u0391-\uFFE5]/g, “aa”).length; // First replace Chinese with two bytes of English , In calculating the length
};
return (jmz.GetLength(text));
};
/**
- Generate 0-9,A-Z Random filename
- @param {num} an Number
- chars [array]
*/
var chars = [‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’, ‘k’, ‘l’, ‘m’, ‘n’, ‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’, ‘x’, ‘y’, ‘z’];
const getrandom = (an) => {
var res = “”;
var index = an || 1;
for (var ia = 0; ia < index; ia++) {
var id = Math.ceil(Math.random() * 35);
res += chars[id];
}
return res;
}
const getrandom2 = (num) => {
// Generate a random number of ten letters and numbers
var arr = [];
var tt = num || 1;
for (var i = 0; i < tt; i++) {
var n = Math.random().toString(36).substr(2, 10);
arr.push(n);
}
// duplicate removal
var ukeys = [];
for (var i = 0; i < arr.length; i++) {
if (ukeys.indexOf(arr[i]) == -1) {
ukeys.push(arr[i]);
}
}
// Array processing , Easy to do Html The document shows
var keys = ‘’;
for (var i = 0; i < ukeys.length; i++) {
// ukeys[i] += ‘
’
keys += ukeys[i]
}
// Get the current timestamp
var time = (new Date()).valueOf();
// console.log(time)
return time + keys;
}
/**
-
Map selection
-
@param {fun} successCallback Successful return function
*/
const choosemaplocation = (successCallback) => {
uni.chooseLocation({
success: (res) => {
typeof successCallback == ‘function’ && successCallback(res)
},
fail: (res) => {
confirm(“ Please allow the applet to access your location ”, function () {
if (uni.openSetting) {
uni.openSetting({
success: (res) => {
// choosemaplocation(succfun);
}
})
} else {
confirm(‘ Current wechat version is too low , Please upgrade wechat or manually allow wechat to obtain your personal information ’, false)
}})
}
})
}
/**
-
Select the wechat receiving address
-
@param {fun} successCallback Successful return function
*/
const choosewxaddress = (successCallback) => {
uni.chooseAddress({
success: res => {
typeof successCallback == ‘function’ && successCallback(res)
},
fail: res => {}
})
}
/**
- Data request method
- @method get
- @param {string} url Address of the interface
- @param {function} successCallback Request successful callback
- @param {function} failCallback Request failed callback
*/
const ajaxget = (url, successCallback, failCallback) => {
uni.request({
url: url,
header: {
‘content-type’: ‘application/x-www-form-urlencoded’
},
success: res => {
var data = res.data
successCallback(data)
},
fail: err => {
failCallback(err)
}
})
}
/**
-
Data request method
-
@method post
-
@param {string} url Address of the interface
-
@param {obj} data Parameters
-
@param {function} successCallback Request successful callback
-
@param {function} funerr Wrong return
*/
const ajaxpost = (url, data, successCallback, funerr) => {
uni.request({
url: url,
method: ‘POST’,
data: data,
header: {
‘content-type’: ‘application/x-www-form-urlencoded’
},
success: res => {
var data = res.data
// console.log(res.data)
if (data.status != 1){
if (data.info == “ Login failure , Please click the avatar to log in ”) {
hideloading();
confirm(data.info, (res) => {
if (res.confirm) {
removeCache(“token”)
uni.reLaunch({ url: ‘/pages/user/user’ })
} else if (res.cancel) {} }, false); } // else if (data.status == 3){ // gopage('/pages/bindphone/bindphone') // } else { hideloading(); if (typeof (funerr) == 'function') { confirm(data.info, (res) => { if (res.confirm) { funerr() } }); } else { confirm(data.info); } }} else {
hideloading()
successCallback(data)
}
},
fail: err => {
hideloading();
showerror(‘ Network error ’);
}
})
}
/** -
Turn seconds into minutes and seconds
-
@method post
-
@param {num} value Number of seconds
/
const formatSeconds = (value) => {
var seconds = parseInt(value);// second
var minute = 0;// branch
var hour = 0;// Hours
var day = 0;// God
if (seconds > 60) {
minute = parseInt(seconds / 60);
seconds = parseInt(seconds % 60);
if (minute > 60) {
hour = parseInt(minute / 60);
minute = parseInt(minute % 60);
if (hour > 24) {
day = parseInt(hour / 24);
hour = parseInt(hour % 24);
}
}
}
var result = “” + parseInt(seconds) + “ second ”;
if (minute > 0) {
result = “” + parseInt(minute) + “ branch ” + result;
}
if (hour > 0) {
result = “” + parseInt(hour) + “ Hours ” + result;
}
if (day > 0) {
result = “” + parseInt(day) + “ God ” + result;
}
return result;
}
/* -
Timestamp conversion
-
@param {num} nS Time stamp
/
const getlocaltime = (nS) => {
return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/, ’ ');
}
/* -
forward
-
@param {title} string Forwarded title
-
@param {path} string Forwarding path
/
const share = (title, path) => {
return {
title: title || ‘ Flash recommendation applet ’,
path: path || ‘/pages/index/index’
}
}
/* -
oss Direct transmission
-
@param {num} nS Time stamp
/
const uploadOss = (api, param, func) => {
uni.uploadFile({
url: api,
filePath: param.path,
name: ‘file’,
header: {
‘content-type’: ‘multipart/form-data’,
‘X-Requested-With’: ‘XMLHttpRequest’
}, // Set the requested header
formData: param, // HTTP Other extras in the request form data
success: function (res) {
console.log(res)
func(res.data)
},
fail: function (res) {
showerror(‘ Network error ’);
},
})
}
/* -
Select Picture
-
@param {count} number Select the number of pictures , Default 9 Zhang
*/
const chooseImage = (count) => {
let filePath = new Promise((resolve, reject) => {
uni.chooseImage({
count: count,
sizeType: ‘compressed’,
sourceType: [‘album’, ‘camera’],
success: res => {
resolve(res.tempFilePaths)
}
})
})
return filePath;
}
const uploadFile = (url, filePath, name, formData) => {
let upload = new Promise((resolve, reject) => {
uni.uploadFile({
url: url,
filePath: filePath,
name: name,
formData: formData || {},
success(res) {
if (res.statusCode == 200) {
let data = JSON.parse(res.data)
resolve(data)
}
}
})
})
return upload;
}
// Convert time format yyyy-MM-dd HH:MM:SS
const getdata = (time = new Date,cFormat)=> {
const format = cFormat || ‘{y}-{m}-{d} {h}:{i}:{s}’
let date
if (typeof time === ‘object’) {
date = time
} else {
if ((typeof time === ‘string’) && (/3+$/.test(time))) {
time = parseInt(time)
}
if ((typeof time === ‘number’) && (time.toString().length === 10)) {
time = time * 1000
}
date = new Date(time)
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
}
const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
const value = formatObj[key]
// Note: getDay() returns 0 on Sunday
if (key === ‘a’) { return [‘ Japan ’, ‘ One ’, ‘ Two ’, ‘ 3、 ... and ’, ‘ Four ’, ‘ 5、 ... and ’, ‘ 6、 ... and ’][value] }
return value.toString().padStart(2, ‘0’)
})
return time_str
}
/**
- Get input
- @param {name} string Parameter name
- @param {e} obj
*/
module.exports = {
trim: trim, // Remove the space before and after the string
alert: alert, // Successful hints
showToast: showToast, // Prompt information
showerror: showerror, // Wrong message
loading: loading, // wait for
hideloading: hideloading, // Hide waiting
confirm: confirm, // Prompt box with button
gopage: gopage, // Page Jump does not close the current page
gotopage: gotopage, // Page Jump closes the current page
gotarpage: gotarpage, // Page Jump tarbar page
backpage: backpage, // Page back
alertBack: alertBack, // The page with pop-up box returns
setCache: setCache, // Add cache ( Sync )
getCache: getCache, // Access to the cache ( Sync )
removeCache: removeCache, // Delete cache
testing: testing, // cell-phone number , Price , password , Number , Non null verification
getstringwidth: getstringwidth, // Get string length ( Chinese to 2 english )
// getrandom: getrandom, // obtain 0-9,a-z Random filename
// getrandom2: getrandom2,
choosemaplocation: choosemaplocation, // Select an address on the map
choosewxaddress: choosewxaddress, // Select wechat harvest address
// ajaxget: ajaxget, //get request
// ajaxpost: ajaxpost, //post request
formatSeconds: formatSeconds, // Turn seconds into days, hours, minutes and seconds
getlocaltime: getlocaltime, // Timestamp conversion
// share: share, // Share
// uploadOss: uploadOss, //oss Direct transmission
// chooseImage: chooseImage, // Select Picture —— choice
// uploadFile: uploadFile, // Select Picture —— Upload
getdata: getdata, // Get the current time
}
版权声明
本文为[Bruce Lee]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204221144440227.html
边栏推荐
猜你喜欢

The second day of playing 51 single chip microcomputer in 14 days -- thought we were playing LED lights? No, no, no, we're playing with the bottom I / O^-^

云中漫步-柴米油盐之上

redis 清除所有库和当前选择的库的数据

怎么得到tuphub.today热榜和热度呢?

微信小程序使用VantUI框架(Vant Weapp) yarn安装

200. 岛屿数量

PTC: 工程机械ESG产品研发重大变革

Basic operation of MySQL
![[security construction] Sysmon, the best tool for log monitoring](/img/24/4cb8565b51423e5756b292ca522a23.png)
[security construction] Sysmon, the best tool for log monitoring

第一章 入门概述
随机推荐
云中漫步-柴米油盐之上
Best practices of Apache APIs IX high availability configuration center based on tidb
LeetCode202. Happy number
【唐老狮】Unity网络通信中的分包、黏包
LeetCode383. Ransom letter
用数字 钥匙 打开发展新空间
深度学习技术开发与应用
(10 pieces of terrain data for offline processing)
云中漫步-旅行到宇宙边缘
2023年东南大学英语笔译考研上岸前辈备考经验指导
golang开发:go并发的建议
活动预告 | 4月23日,多场OpenMLDB精彩分享来袭,不负周末好时光!
LeetCode454. 四数相加 II
原来,这才是开发者打开世界读书日的正确姿势!
Pytorch量化(torch.quantization)
leetcode:347. 前 K 个高频元素
半小时理解JSP
200. 岛屿数量
微信支付宝小程序支付页面
智慧党建综合管理平台开发,数字党建一体化管理系统