let tool = {
tansParams(params) {
let result = ''
for (const propName of Object.keys(params)) {
const value = params[propName]
var part = encodeURIComponent(propName) + "="
if (value !== null && value !== "" && typeof(value) !== "undefined") {
if (typeof value === 'object') {
for (const key of Object.keys(value)) {
if (value[key] !== null && value[key] !== "" && typeof(value[key]) !== 'undefined') {
let params = propName + '[' + key + ']'
var subPart = encodeURIComponent(params) + "="
result += subPart + encodeURIComponent(value[key]) + "&"
}
}
} else {
result += part + encodeURIComponent(value) + "&"
}
}
}
return result
},
// 模态弹窗
// content:文字信息
showConfirm(content) {
return new Promise((resolve, reject) => {
uni.showModal({
title: '提示',
content: content,
cancelText: '取消',
confirmText: '确定',
success: function(res) {
resolve(res)
}
})
})
},
// 挂载页面loadingbox
// title:标题 time:时间
loadingFn(title, time) {
uni.showLoading({
title: title,
});
setTimeout(function() {
uni.hideLoading()
}, time);
},
// 断网
isHaveNetwork() {
uni.getNetworkType({
success: (res) => {
if (res.networkType == 'none') {
uni.showModal({
title: '当前无网络连接!',
content: '请您检查网络是否链接正常!请打开WIFI或者移动数据。',
success: (res) => {
if (res.confirm) {
uni.navigateTo({
url: '/pages/404/404.vue'
})
} else {
uni.navigateTo({
url: '/pages/404/404.vue'
})
}
}
});
} else {
console.log('网络已连接,可以正常访问!') //有网
}
setTimeout(function() {
return res.networkType
}, 500);
}
});
},
// 获取小程序的appId
getAppId() {
return uni.getAccountInfoSync ? uni.getAccountInfoSync().miniProgram.appId : '';
},
// 获取经纬度
uniGetLocation({
type = 'wgs84',
...moreOptions
} = {}) {
return new Promise((resolve) => {
uni.getLocation({
type,
success({
longitude,
latitude
}) {
console.log(`当前位置的经度:${longitude}`);
console.log(`当前位置的纬度:${latitude}`);
resolve({
longitude,
latitude,
});
},
...moreOptions,
});
});
},
// 调起内置地图选择位置
uniChooseLocation({
...moreOptions
} = {}) {
return new Promise((resolve) => {
uni.chooseLocation({
success(res) {
console.log('uni.chooseLocation.res', res);
const {
address,
latitude,
longitude,
name,
} = res;
resolve({
status: true,
address,
latitude,
longitude,
name,
});
},
fail(err) {
console.log('uni.chooseLocation.err', err);
resolve({
status: false,
address: '',
latitude: 0,
longitude: 0,
});
},
...moreOptions,
});
});
},
// /**
// * uniapp获取经纬度
// */
// uniOpenLocation({
// latitude = 39.909,
// longitude = 116.39742,
// ...moreOptions
// } = {}) {
// return new Promise((resolve) => {
// uni.openLocation({
// latitude,
// longitude,
// success(res) {
// console.log('uni.uniOpenLocation.res', res);
// resolve({
// status: true
// });
// },
// fail(err) {
// console.log('uni.uniOpenLocation.err', err);
// resolve({
// status: false
// });
// },
// ...moreOptions,
// });
// });
// },
/**
* 参数处理
*/
// 授权登录提示框
// url:要跳转的地址
pleaseLoginTipBox(url) {
uni.showModal({
title: '温馨提示',
content: '您尚未完成微信授权或手机号授权,建议授权以便获得更好的体验!',
cancelText: "取消",
confirmText: "去授权",
showCancel: true,
confirmColor: '#4e6ef2',
cancelColor: '#333',
success: (res) => {
if (res.confirm) {
uni.navigateTo({
url: url
})
} else {
console.log('任然取消授权');
uni.navigateBack({
delta: 1
})
}
}
})
},
// toast提示框
// 标题,图标,存在时间
toastTip(title, icon, time) {
uni.showToast({
title: title || '网络连接超时,请稍后重试!',
icon: icon || 'none',
duration: time || 1500
})
},
// Loading加载提示框
// 标题
showLoading(title) {
uni.showLoading({
title: title
})
},
// 时间戳转换为年月日(XiaoZhou-1999-10-30)
getBirthday(timestamp) {
let date = new Date(timestamp);
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
month = month < 10 ? "0" + month : month;
day = day < 10 ? "0" + day : day;
return year + '-' + month + '-' + day;
},
// 获取字符串的真实长度(字节长度)
strLeng(str) {
if (str) {
let len = str.length,
truelen = 0;
for (let x = 0; x < len; x++) {
if (str.charCodeAt(x) > 128) {
truelen += 2;
} else {
truelen += 1;
}
}
return truelen;
} else {
return 0;
}
},
// 获取最近一周的时间
getWeekTime() {
//现在的时间
var arr = [];
var dates = new Date();
dates.setDate(dates.getDate() + 1);
let year = dates.getFullYear();
let mounth = (dates.getMonth() + 1).toString().padStart(2, '0');
let day = dates.getDate().toString().padStart(2, '0');
let hour = dates.getHours().toString().padStart(2, '0');
let minutes = dates.getMinutes().toString().padStart(2, '0');
arr[0] = year + '-' + mounth + '-' + day + ' ' + hour + ':' + minutes + ':' + '00';
// 一周前的时间
var time = (new Date()).getTime() - 7 * 24 * 60 * 60 * 1000;
var tragetTime = new Date(time);
let tyear = tragetTime.getFullYear();
let tmounth = (tragetTime.getMonth() + 1).toString().padStart(2, '0');
let tday = tragetTime.getDate().toString().padStart(2, '0');
let thour = tragetTime.getHours().toString().padStart(2, '0');
let tminutes = tragetTime.getMinutes().toString().padStart(2, '0');
arr[1] = tyear + '-' + tmounth + '-' + tday + ' ' + thour + ':' + tminutes + ':' + '00';
return arr
},
// 计算页数
getPageNum(total, row) {
let num = Number(total) / Number(row);
//是否为整数
if (num % 1 !== 0) {
let b = num.toString(); //转字符串
let a = parseInt(b.substring(0, b.indexOf('.'))); //取小数点前
let s = b.replace(/\d+\.(\d*)/, '$1'); //取小数点后
if (s > 0) {
num = a + 1;
}
}
return num;
},
// 日期格式化
formatDate(time) {
// ios的时间
// 将xxxx-xx-xx的时间格式,转换为 xxxx/xx/xx的格式
return time.replace(/\-/g, "/");
},
// 遍历对象
objForEach(obj, callback) {
Object.keys(obj).forEach((key) => {
callback(obj[key], key)
});
},
// 是否在数组内
inArray(search, array) {
for (var i in array) {
if (array[i] == search) return true
}
return false
},
// 是否为空对象
isEmptyObject(object) {
return Object.keys(object).length === 0
},
//防抖
debounce(fn, delay) {
let timer
return function() {
const that = this
const _args = arguments // 存一下传入的参数
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(function() {
fn.apply(that, _args)
}, delay)
}
},
// 节流
throttle(fn, gapTime) {
if (gapTime == null || gapTime == undefined) {
gapTime = 1500
}
let _lastTime = null
// 返回新的函数
return function() {
let _nowTime = +new Date()
if (_nowTime - _lastTime > gapTime || !_lastTime) {
fn.apply(this, arguments) //将this和参数传给原函数
_lastTime = _nowTime
}
}
},
// 金钱显示为xxx,xxx.xx
formatMoney(money, digit = 2) {
var tpMoney = '0.00'
if (undefined !== money) {
tpMoney = money
}
tpMoney = Number(tpMoney)
if (isNaN(tpMoney)) {
return '0.00'
}
tpMoney = tpMoney.toFixed(digit) + ''
var re = /^(-?\d+)(\d{3})(\.?\d*)/
while (re.test(tpMoney)) {
tpMoney = tpMoney.replace(re, '$1,$2$3')
}
return tpMoney
},
// 大于99的数字变成99+
numLimit(value) {
return value > 99 ? '99+' : value
},
// 距离米和千米
distance(value) {
if (value === null || value === undefined) {
return '--'
} else if (value < 1000) {
return value + ' m'
} else {
return (value / 1000).toFixed(1) + ' km'
}
},
// 数量过万截取
amount(value, unit = '万') {
if (value === null || value === undefined) {
return '--'
} else if (value < 10000) {
return value
} else {
return (value / 10000).toFixed(1) + unit
}
},
// 卡号加***
bindCardNo(value) {
if (value) {
const arr1 = value.substr(value.length - 4)
const arr2 = value.substr(0, 4)
return arr2 + ' **** **** **** ' + arr1
}
},
sliceString(str, max = 20) { // 字符串限制长度 超出部分隐藏显示...
if (!str || str.length === 0) {
return ''
}
if (str.length > max) {
str = str.substring(0, max)
str += '...'
}
return str
},
arrToStr(arr = []) { // 数组处理为字符串用‘,’隔开
var str = ''
var len = arr.length
for (var i = 0; i < len; i++) {
if (i >= 1) {
str += ','
}
str += arr[i]
}
return str
},
lessTen(num = 0) { // 数字小于10显示01-09
var newNum = parseInt(num)
return newNum < 10 ? '0' + newNum : newNum
},
capital(str = '') { // 数字转换为大写汉字
str = str + ''
var len = str.length - 1
var idxs = ['', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万', '十', '百', '千', '亿']
var num = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
return str.replace(/([1-9]|0+)/g, function($, $1, idx, full) {
var pos = 0
if ($1[0] !== '0') {
pos = len - idx
if (idx === 0 && $1[0] === 1 && idxs[len - idx] === '十') {
return idxs[len - idx]
}
return num[$1[0]] + idxs[len - idx]
} else {
var left = len - idx
var right = len - idx + $1.length
if (Math.floor(right / 4) - Math.floor(left / 4) > 0) {
pos = left - left % 4
}
if (pos) {
return idxs[pos] + num[$1[0]]
} else if (idx + $1.length >= len) {
return ''
} else {
return num[$1[0]]
}
}
})
},
secondToTime(sec = 0) { // 秒数转换成时分秒格式
if (sec < 3600) {
return (
tools.lessTen(Math.floor(parseInt(sec) / 60)) +
':' +
tools.lessTen(parseInt(sec) % 60)
)
} else {
return (
tools.lessTen(Math.floor(parseInt(sec) / 3600)) +
':' +
tools.lessTen(Math.floor((parseInt(sec) % 3600) / 60)) +
':' +
tools.lessTen(parseInt(sec) % 60)
)
}
},
handlePhone(val) { // 手机号中间四位隐藏
var phone = val.substr(0, 3) + '****' + val.substr(7)
return phone
},
secondToDate(result) { //时间转化时分秒
var h = Math.floor(result / 3600) < 10 ? '0' + Math.floor(result / 3600) : Math.floor(result / 3600)
var m = Math.floor((result / 60 % 60)) < 10 ? '0' + Math.floor((result / 60 % 60)) : Math.floor((result / 60 %
60))
var s = Math.floor((result % 60)) < 10 ? '0' + Math.floor((result % 60)) : Math.floor((result % 60))
return h + ':' + m + ':' + s
},
getValforObj(obj, val) { //获取对象的值
return obj[val]
},
getDateTime() { // 获取当前时间
var dt = new Date()
var year = dt.getFullYear()
var month = dt.getMonth() + 1
var day = dt.getDate()
// var h = dt.getHours()
// var m = dt.getMinutes()
// var s = dt.getSeconds()
month = (parseInt(month) < 10 ? '0' : '') + month
day = (parseInt(day) < 10 ? '0' : '') + day
var currentdate = year + '-' + month + '-' + day
return currentdate
},
getWeekday(dt, str) { // 获取传入日期 str为空时默认返回星期几
str = str || '星期'
var index = dt.getDay()
var arr = ['天', '一', '二', '三', '四', '五', '六']
var wd = arr[index]
return str + wd
},
getDateDiff(dt) { // 获取传入时间与当前时间的差
dt = new Date(dt).getTime()
var minute = 1000 * 60
var hour = minute * 60
var day = hour * 24
var month = day * 30
var now = new Date().getTime()
var diff = now - dt
if (diff < 0) return
var monthC = diff / month
var weekC = diff / (7 * day)
var dayC = diff / day
var hourC = diff / hour
var minC = diff / minute
var result = ''
if (monthC >= 1) {
result = '' + parseInt(monthC) + '个月前'
} else if (weekC >= 1) {
result = '' + parseInt(weekC) + '周前'
} else if (dayC >= 1) {
result = '' + parseInt(dayC) + '天前'
} else if (hourC >= 1) {
result = '' + parseInt(hourC) + '小时前'
} else if (minC >= 1) {
result = '' + parseInt(minC) + '分钟前'
} else {
result = '刚刚'
}
return result
},
getDateByCount(dt, acount, sign) { // 传入日期dt 获取acount天后的日期 sign默认为/
sign = sign || '/'
var dd = new Date(dt)
dd.setDate(dd.getDate() + acount * 1)
// 获取acount天后的日期
var y = dd.getFullYear()
var m = dd.getMonth() + 1
// 获取当前月份的日期
var d = dd.getDate()
if (m < 10) {
m = '0' + m
}
if (d < 10) {
d = '0' + d
}
return y + sign + m + sign + d
},
handelTime(sec = 0) { // 处理时间格式 return[天,小时,分钟,秒]
let d = 0
let h = 0
let m = 0
let s = parseInt(sec)
if (s >= 60) {
m = parseInt(sec / 60)
s = parseInt(sec % 60)
if (m >= 60) {
h = parseInt(m / 60)
m = parseInt(m % 60)
if (h >= 24) {
d = parseInt(h / 24)
h = parseInt(h % 24)
}
}
}
return [d, h, m, s]
},
getParams(url) { // 获取链接中包含的参数
const paramObj = {}
const params = url.split('?')[1]
if (!params) return paramObj
const keyValueArr = params.split('&')
keyValueArr.forEach(item => {
const keyValue = item.split('=')
paramObj[keyValue[0]] = decodeURIComponent(keyValue[1])
})
return paramObj
},
executeExp(r, v) { // 进行校验
if (!v) return false
return r.test(v)
},
isMobile(v = '') { // 判断是否为手机号码
var r = /^1[3456789]\d{9}$/ // 最新手机号校验 ---- 2020-07-01改
return !v ? false : r.test(v)
},
isPassword(v = '') { // 判断密码
var r = /^[a-zA-Z0-9]{6,14}$/
return !v ? false : r.test(v)
},
isMobile2(v = '') { // 判断是否为固定电话号码
var r = /^(0[0-9]{2,3}\-)([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/
return tools.executeExp(r, v)
},
isCardID(v = '') { // 验证身份证的有效性
var r = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
// return tools.executeExp(r, v)
return !v ? false : r.test(v)
},
isEmail(v = '') {
var r = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/
return tools.executeExp(r, v)
},
idChinese(v = '') { // 判断是否为汉字
var r = /^\s*$/g
if (!v) return false
return r.test(v)
},
isPlateNumber(v = '') { // 判断是否为车牌号
var r = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/
return tools.executeExp(r, v)
},
isPrime(v = '') { // 判断数字是否为质数
return !(/^.?$|^(..+?)\1+$/).test('1'.repeat(v))
},
isPhoto(u = '') { // 判断图片格式是否符合要求
var _index = u.lastIndexOf('.')
var _type = u.substring(_index + 1)
var _types = ['jpg', 'png', 'gif']
return !(_types.indexOf(_type) <= -1)
},
isMoney(v = '') { // 判断是否为整数,或者最多保留两位小数
var r = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
return r.test(v)
},
isAge(v = '') { // 判断是否为正整数(1-120)
var r = /^(?:[1-9][0-9]?|1[01][0-9]|120)$/
return r.test(v)
},
// 判断设备类型
device() {
const u = navigator.userAgent
const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 // android终端
const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) // ios终端
if (isAndroid) {
return 'android'
}
if (isiOS) {
return 'ios'
}
},
};
export default tool;
uniApp常用功能封装
最新推荐文章于 2024-09-29 10:18:10 发布