Files
sweekar-app/common/common.js
T
2026-01-04 17:53:40 +08:00

1062 lines
27 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {
pinyin
} from 'pinyin-pro';
import crypto from 'crypto-js';
/**
* @desc 获取当天日期 格式yyyy-MM-dd HH:mm:ss
*/
export const getFullNowDate = () => {
const date = new Date();
const day = date.getDate() < 10 ? '0' + String(date.getDate()) : date.getDate();
const month = date.getMonth() + 1 < 10 ? '0' + String(date.getMonth() + 1) : date.getMonth() + 1;
const year = date.getFullYear();
const hour = date.getHours() < 10 ? '0' + String(date.getHours()) : date.getHours();
const minue = date.getMinutes() < 10 ? '0' + String(date.getMinutes()) : date.getMinutes();
const second = date.getSeconds() < 10 ? '0' + String(date.getSeconds()) : date.getSeconds();
return year + '-' + month + '-' + day + ' ' + hour + ':' + minue + ':' + second;
};
/**
* @desc 获取当天日期 格式yyyy-MM-dd HH:mm
*/
export const getNowDateYMDms = () => {
const date = new Date();
const day = date.getDate() < 10 ? '0' + String(date.getDate()) : date.getDate();
const month = date.getMonth() + 1 < 10 ? '0' + String(date.getMonth() + 1) : date.getMonth() + 1;
const year = date.getFullYear();
const hour = date.getHours() < 10 ? '0' + String(date.getHours()) : date.getHours();
const minue = date.getMinutes() < 10 ? '0' + String(date.getMinutes()) : date.getMinutes();
const second = date.getSeconds() < 10 ? '0' + String(date.getSeconds()) : date.getSeconds();
return year + '-' + month + '-' + day + ' ' + hour + ':' + minue;
};
/**
* @desc 获取当天日期 格式yyyy-MM-dd
*/
export const getNowDate = () => {
const date = new Date();
const day = date.getDate() < 10 ? '0' + String(date.getDate()) : date.getDate();
const month = date.getMonth() + 1 < 10 ? '0' + String(date.getMonth() + 1) : date.getMonth() + 1;
const year = date.getFullYear();
return year + '-' + month + '-' + day;
};
// 获取下一天日期 格式yyyy年MM月dd日
export const getNextDate = () => {
const date = new Date();
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
// 检查是否是本月的最后一天
if (new Date(year, month, 0).getDate() === day) {
// 如果是月份的最后一天
if (month === 12) {
// 如果是12月,则变为下一年的1月
year += 1;
month = 1;
} else {
// 否则,月份+1
month += 1;
}
day = 1; // 下一个月的第一天
} else {
day += 1; // 否则,日期+1
}
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
// console.log(year + "-" + month + "-" + day);
return year + '-' + month + '-' + day;
};
/**
* @desc 將Date日期根據分隔符輸出
* @param data 日期date格式
* @param split 日期分隔符
*/
export const returnDateBySplit = (data, split) => {
const date = new Date(data);
const day = date.getDate() < 10 ? '0' + String(date.getDate()) : date.getDate();
const month = date.getMonth() + 1 < 10 ? '0' + String(date.getMonth() + 1) : date.getMonth() + 1;
const year = date.getFullYear();
return [year, month, day].join(split);
};
/**
* @desc 根据日期返回MM月dd日
*/
export const returnDateForMonthDay = (data) => {
const date = new Date(data);
const day = date.getDate() < 10 ? '0' + String(date.getDate()) : date.getDate();
const month = date.getMonth() + 1 < 10 ? '0' + String(date.getMonth() + 1) : date.getMonth() + 1;
return month + '月' + day + '日';
};
/**
* @desc 将输入的时间戳返回其对应的format格式
*/
export const formatTimestamp = (remainingMs) => {
const days = Math.floor(remainingMs / (1000 * 60 * 60 * 24));
const hours = Math.floor((remainingMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((remainingMs % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((remainingMs % (1000 * 60)) / 1000);
return `${days > 0 ? days + '天' : ''}${hours > 0 ? hours + '时' : ''}${minutes > 0 ? minutes + '分' : ''}${
seconds > 0 || (days === 0 && hours === 0 && minutes === 0) ? seconds + '秒' : ''
}`;
};
/**
* @desc 根据count-down组件倒计时change方法返回format
*/
export const setCountDownFormat = (count) => {
const days = count.days;
const hours = count.hours;
const minutes = count.minutes;
const seconds = count.seconds;
return `${days > 0 ? days + '天' : ''}${hours > 0 ? hours + '时' : ''}${minutes > 0 ? minutes + '分' : ''}${
seconds > 0 || (days === 0 && hours === 0 && minutes === 0) ? seconds + '秒' : ''
}`;
};
/**
* @desc 去除字符串两头指定符号
*/
export const trimChars = (str, charToTrim) => {
// 使用正则表达式,g标志表示全局匹配,以去除所有两端的字符
const regex = new RegExp(`^[${charToTrim}]+|[${charToTrim}]+$`, 'g');
return str.replace(regex, '');
};
// 计算日期为周几
export const getWeek = (dateString) => {
const date = new Date(dateString);
const weekDay = ['週日', '週一', '週二', '週三', '週四', '週五', '週六'];
return weekDay[date.getDay()];
};
/**
* @desc 获取当月从当日到末日的日期
*/
export const getDayNum = () => {
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth() + 1 < 10 ? '0' + String(date.getMonth() + 1) : date.getMonth() + 1;
let today = date.getDate() < 10 ? '0' + String(date.getDate()) : date.getDate();
let yearMonthDay = '';
let dayList = [];
// 当月剩余天数(包括当天)
let days = new Date(year, month, today);
// 当月总天数
let allDays = new Date(year, month, 0);
// 返回日期
for (var i = days.getDate(); i <= allDays.getDate(); i++) {
yearMonthDay = year + '/' + month + '/' + i;
dayList.push(yearMonthDay);
}
return dayList;
};
/**
*
* @param {*} obj 需拷貝的對象
* @param {*} deep 深拷貝為true,默認false
* @returns
*/
export function useClone(obj, deep = false) {
// 处理非对象或null的情况
if (obj === null || typeof obj !== 'object') {
return obj;
}
// 处理深拷贝
if (deep) {
// 使用递归和WeakMap处理循环引用
const seen = new WeakMap();
function deepClone(x) {
// 处理循环引用
if (seen.has(x)) {
return seen.get(x);
}
// 处理基本类型和函数
if (typeof x !== 'object' || x === null || typeof x === 'function' || typeof x === 'symbol') {
return x;
}
// 初始化拷贝对象
let copy;
if (Array.isArray(x)) {
copy = [];
} else {
copy = {};
}
// 存储拷贝对象和原始对象的映射关系
seen.set(x, copy);
// 递归拷贝每个属性
for (const key in x) {
if (x.hasOwnProperty(key)) {
copy[key] = deepClone(x[key]);
}
}
return copy;
}
return deepClone(obj);
}
// 处理浅拷贝
const shallowCopy = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
shallowCopy[key] = obj[key];
}
}
return shallowCopy;
}
/**
* @desc 重新生成新的日期list
*/
export const changeDateList = (limit) => {
// 比如今天是2023-03-17,将今天及之后44天日期都push进list
// 获取今日日期
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth() + 1 < 10 ? '0' + String(date.getMonth() + 1) : date.getMonth() + 1;
let day = date.getDate() < 10 ? '0' + String(date.getDate()) : date.getDate();
// 定义新数组
let dayList = [];
// 当月今天是第days日
let days = new Date(year + '-' + month + '-' + day);
// 当月总天数
let allDays = new Date(year, month, 0);
let yearMonthDay = '';
// 返回当月剩余日期
if (allDays.getDate() - day === 0) {
// 当月最后一天
days = allDays;
}
for (var i = days.getDate(); i <= allDays.getDate(); i++) {
yearMonthDay = year + '/' + month + '/' + (i < 10 ? '0' + i : i);
dayList.push(yearMonthDay);
}
// 计算之间日期
while (dayList.length < limit) {
let remainderDays = '';
if (Number(month) + 1 > 12) {
month = 1;
year += 1;
} else {
month = Number(month) + 1;
}
remainderDays = new Date(Number(year), Number(month), 0).getDate();
for (var i = 1; i <= remainderDays; i++) {
let cuptMonth = Number(month) < 10 ? '0' + Number(month) : Number(month);
let cuptDay = i < 10 ? '0' + i : i;
yearMonthDay = year + '/' + cuptMonth + '/' + cuptDay;
dayList.push(yearMonthDay);
if (dayList.length === limit) {
break;
}
}
}
return dayList;
};
/**
* @desc 比较两个日期时间大小 返回較大的日期
* @param {string} firTime 时间一
* @param {string} secTime 时间二
* @returns {string} 时间
*/
export const compareDateToLarge = (firTime, secTime) => {
if (!firTime || !secTime) return getNowDate();
let firTimeStamp = new Date(firTime).getTime();
let secTimeStamp = new Date(secTime).getTime();
let diffTimeStamp = firTimeStamp - secTimeStamp;
let returnDate = '';
if (diffTimeStamp < 0) {
// 今天日期 - 当前日期 小于0 ,表示当前日期有效
returnDate = secTime;
} else {
// 今天日期 - 当前日期 大于等于0 ,表示当前日期无效
returnDate = firTime;
}
return returnDate;
};
/**
* @desc 日期转时间戳
* @value date 需要转换成时间戳的日期
* @return timeStamp 时间戳
*/
export const transferDateToTimestamp = (date) => {
return new Date(date).getTime();
};
/**
* @desc 指定日期是否在指定小时内
* @value date1 round
* @return false 在24小时内 true超过24小时
*/
export const computedDateInRound = (date1, round) => {
let time1 = transferDateToTimestamp(date1);
let time2 = time1 + round * 60 * 60 * 1000;
let roundStamp = round * 60 * 60 * 1000;
let nowTimeStamp = transferDateToTimestamp(getFullNowDate());
let diffTime = nowTimeStamp - time2;
// 大于0,表示过期
if (diffTime > 0) {
return true;
} else {
return false;
}
};
/**
* 先对content执行trim 去掉左右两边的空格
取出code中的所有数字
执行md5(所有数字+','+content)= mdCode
返回字符串:code+'-'+mdCode
* @param {*} code
* @param {*} content
*/
export const createV = (code, content) => {
const nums = code.trim().match(/[0-9]/g).join('');
const deText = crypto.MD5(`${nums},${content}`).toString();
return `${code.trim()}-${deText}`;
};
/**
* @desc 时间戳转日期
* @return yyyy-MM-dd
*/
export const operaTimeStamp = (time) => {
var date = new Date(time);
var Y = date.getFullYear() + '-';
var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
return Y + M + D;
};
/**
* @desc 时间戳转日期
* @return yyyy-MM-dd
*/
export const operaFullTimeStamp = (time) => {
var date = new Date(time);
var Y = date.getFullYear() + '-';
var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
var H = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
return Y + M + D + ' ' + H + ':' + m + ':' + s;
};
/**
* @description 格式化时间
* @param {String|Number} dateTime 需要格式化的时间戳
* @param {String} fmt 格式化规则 yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合 默认yyyy-mm-dd
* @returns {string} 返回格式化后的字符串
*/
export const timeFormat = (dateTime = null, formatStr = 'yyyy-mm-dd') => {
let date;
// 若传入时间为假值,则取当前时间
if (!dateTime) {
date = new Date();
}
// 若为unix秒时间戳,则转为毫秒时间戳(逻辑有点奇怪,但不敢改,以保证历史兼容)
else if (/^\d{10}$/.test(dateTime.toString().trim())) {
date = new Date(dateTime * 1000);
}
// 若用户传入字符串格式时间戳,new Date无法解析,需做兼容
else if (typeof dateTime === 'string' && /^\d+$/.test(dateTime.trim())) {
date = new Date(Number(dateTime));
}
// 其他都认为符合 RFC 2822 规范
else {
// 处理平台性差异,在Safari/Webkit中,new Date仅支持/作为分割符的字符串时间
date = new Date(typeof dateTime === 'string' ? dateTime.replace(/-/g, '/') : dateTime);
}
const timeSource = {
y: date.getFullYear().toString(), // 年
m: (date.getMonth() + 1).toString().padStart(2, '0'), // 月
d: date.getDate().toString().padStart(2, '0'), // 日
h: date.getHours().toString().padStart(2, '0'), // 时
M: date.getMinutes().toString().padStart(2, '0'), // 分
s: date.getSeconds().toString().padStart(2, '0'), // 秒
// 有其他格式化字符需求可以继续添加,必须转化成字符串
};
for (const key in timeSource) {
const [ret] = new RegExp(`${key}+`).exec(formatStr) || [];
if (ret) {
// 年可能只需展示两位
const beginIndex = key === 'y' && ret.length === 2 ? 2 : 0;
formatStr = formatStr.replace(ret, timeSource[key].slice(beginIndex));
}
}
return formatStr;
};
/**
* @desc 判断是否为空
*/
export const isEmpty = (value) => {
switch (typeof value) {
case 'undefined':
return true;
case 'string':
if (value.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, '').length == 0) return true;
break;
case 'boolean':
if (!value) return true;
break;
case 'number':
if (value === 0 || isNaN(value)) return true;
break;
case 'object':
if (value === null || value.length === 0) return true;
for (const i in value) {
return false;
}
return true;
}
return false;
};
/**
@desc 获取用户定位
*/
export const getUserLocation = () => {
return new Promise((resolve, reject) => {
const location = {
latitude: 0,
longitude: 0,
};
uni.getLocation({
isHighAccuracy: true,
altitude: true,
type: 'gcj02',
success(res) {
location.latitude = res.latitude;
location.longitude = res.longitude;
resolve(location);
},
fail() {
resolve(location);
},
});
});
};
/**
@desc 计算两个坐标之间的经纬度差值
*/
export const getGreatCircleDistance = (lat1, lng1, lat2, lng2) => {
let EARTH_RADIUS = 6378137.0; //单位m
let PI = Math.PI;
function getRad(d) {
return (d * PI) / 180.0;
}
let radLat1 = getRad(lat1);
let radLat2 = getRad(lat2);
let a = radLat1 - radLat2;
let b = getRad(lng1) - getRad(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 * EARTH_RADIUS;
s = Math.round(s * 10000) / 10000.0;
return s;
};
/**
@desc 计算两个坐标之间的经纬度差值
*/
export const getDistance = (lat1, lon1, lat2, lon2) => {
const R = 6378137; // 地球半径,单位米
const phi1 = (lat1 * Math.PI) / 180; // 纬度1,弧度制
const phi2 = (lat2 * Math.PI) / 180; // 纬度2,弧度制
const phiDelta = ((lat2 - lat1) * Math.PI) / 180; // 两点纬度差,弧度制
const lambdaDelta = ((lon2 - lon1) * Math.PI) / 180; // 两点经度差,弧度制
const a = Math.sin(phiDelta / 2) * Math.sin(phiDelta / 2) + Math.cos(phi1) * Math.cos(phi2) * Math.sin(
lambdaDelta / 2) * Math.sin(lambdaDelta / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
const distance = R * c;
return distance;
};
/**
* @desc 计算两个坐标间距离,单位米、千米
* @param coord1 坐标1
* @param coord2 坐标2
*/
export const calculateDistance = (coord1, coord2) => {
const cord1 = coord1.split(',');
const cord2 = coord2.split(',');
const cordObj1 = {
lat: cord1[0],
lng: cord1[1],
};
const cordObj2 = {
lat: cord2[0],
lng: cord2[1],
};
const earthRadius = 6371000; // Earth radius in meters
const lat1 = (cordObj1.lat * Math.PI) / 180; // Convert to radians
const lat2 = (cordObj2.lat * Math.PI) / 180;
const deltaLat = ((cordObj2.lat - cordObj1.lat) * Math.PI) / 180;
const deltaLon = ((cordObj2.lng - cordObj1.lng) * Math.PI) / 180;
const a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) + Math.cos(lat1) * Math.cos(lat2) * Math.sin(
deltaLon / 2) * Math.sin(deltaLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
const distance = earthRadius * c;
return Number(distance) >= 1000 ? (Number(distance) * 0.001).toFixed(1) + 'km' : Number(distance).toFixed(1) +
'm';
// 使用示例
// const cordObj1 = { lat: 52.2296756, lng: 21.0122287 };
// const cordObj2 = { lat: 41.8919300, lng: 12.5113300 };
// console.log(calculateDistance(cordObj1, cordObj2)); // 输出将以米为单位的距离
};
/**
@desc 获取小程序菜单按钮布局信息
平台差异:H5没有此方法,wx、zfb可以获取右上角胶囊按钮的样式
*/
export const getMenuButtonBounding = () => {
const menuStyle = uni.getMenuButtonBoundingClientRect();
return menuStyle;
};
/**
@desc 同步获取设备信息
@return device:运行应用的设备,如iphone、huawei
@return os:设备的操作系统,如 ios、andriod、windows、mac、linux
@return rom:基于操作系统的定制,Android系统特有概念,如miui、鸿蒙
@return host:运行应用的宿主程序,即OS和应用之间的运行环境,如浏览器、微信等小程序宿主、集成uniMPSDK的App。uni-app直接开发的app没有host概念
@return uni:uni-app框架相关的信息,如uni-app框架的编译器版本、运行时版本
@return app:开发者的应用相关的信息,如应用名称、版本
*/
export const getSystemInfo = () => {
let res = uni.getSystemInfoSync();
return res;
};
/**
* @desc 计算顶部bar高度
*/
export const getSafeTopHeight = () => {
let res = uni.getSystemInfoSync();
// #ifdef MP-WEIXIN
return 44 + res.statusBarHeight;
// #endif
// #ifndef MP-WEIXIN
return res.statusBarHeight;
// #endif
};
/**
* @desc 获取底部安全距离高度
*/
export const getSafeAreaBottom = () => {
const {
safeAreaInsets,
osName
} = uni.getSystemInfoSync();
return osName == 'ios' ? safeAreaInsets.bottom : 0;
};
/**
* @desc 计算系统可用安全高度,适配iOS和Android
*/
export const getSystemSafeArea = () => {
// 获取系统信息
const systemInfo = uni.getSystemInfoSync();
// 基础高度信息
var windowHeight = systemInfo.windowHeight;
const statusBarHeight = systemInfo.statusBarHeight || 0;
// iOS设备
// if (systemInfo.osName === 'ios') {
// return windowHeight;
// }
// // Android设备
// else {
// // const titleBarHeight = systemInfo.titleBarHeight || 0;
// // return windowHeight - statusBarHeight - titleBarHeight;
// return windowHeight;
// }
return windowHeight;
};
/**
* @desc H5获取url携带的参数
*/
export const getUrlParams = () => {
const params = {};
const url = window.location.href;
// 解析URL并获取查询参数部分
var queryParams = url.indexOf('?') !== -1 ? url.split('?')[1] : '';
if (queryParams) {
queryParams.split('&').forEach(function(param) {
var keyValuePair = param.split('=');
if (keyValuePair.length > 1) {
var key = decodeURIComponent(keyValuePair[0]);
var value = decodeURIComponent(keyValuePair[1] || '');
params[key] = value;
}
});
}
return params;
};
// 定义一个函数,用于将单个字符串的首字母大写
export const capitalizeFirstLetter = (str) => {
return str.charAt(0).toUpperCase() + str.slice(1);
};
/**
* @desc 中文转拼音
* @value chineseName 中文名
* @return [xing,ming]
*/
export const chineseToPinyin = (chineseName) => {
const pinyinArray = pinyin(chineseName, {
toneType: 'none',
type: 'array',
});
let [xin, ...min] = pinyinArray.map((item) => capitalizeFirstLetter(item));
return [xin, min.join('')];
};
/**
* 字符串的转拼音
* @param {string} chineseName 中文名
* @returns {Array} [xing,ming]
*/
export const chineseNameToPinyin = (chineseName) => {
const pinyinArray = pinyin(chineseName, {
toneType: 'none',
type: 'array',
});
let [xin, ...min] = pinyinArray;
return [xin, min.join('')];
};
/**
* @desc svg图片转base64
*/
export const imgUrl = (url) => {
return `data:image/svg+xml;base64,${encodeURIComponent(url)}`;
};
/**
* @desc 检查字符串是否包含中文
*/
export const checkChinese = (str) => {
var pattern = new RegExp('[\u4E00-\u9FA5]+');
var patternNum = new RegExp('[0-9]+');
if (pattern.test(str)) {
return true;
}
if (patternNum.test(str)) {
return true;
}
return false;
};
/**
* @desc 根据输入的日期返回当前日期是否还在此日期范围内,是返回true
* @param nowDate 当前日期
* @param limit 限定日期
* @return true 在限定日期范围内
*/
export const checkDateUseful = (nowDate, limit) => {
let limitDate = transferDateToTimestamp(limit);
let useDate = transferDateToTimestamp(nowDate);
if (useDate <= limitDate) {
return true;
} else {
return false;
}
};
/**
* @desc 去重
* @param {Array} arrays
*/
export const removeRepeat = (arrays) => {
const uniqueArray = Array.from(new Set(arrays));
return uniqueArray;
};
/**
* @desc 合并一维数组内所有值
* @param {Array} arrays
*/
export const combineArrays1 = (arrays) => {
// 使用 reduce 方法来合并所有的一维数组
const combinedArray = arrays.reduce((acc, currentArray) => acc.concat(currentArray), []);
return combinedArray;
};
/**
* @desc 合并两个一维数组
* @param {Array} arr1
* @param {Array} arr2
*/
export const combineArrays2 = (arr1, arr2) => {
let result = [];
// 遍历第一个数组
for (let i = 0; i < arr1.length; i++) {
// 遍历第二个数组
for (let j = 0; j < arr2.length; j++) {
// 组合成一个新的数组
let combination = [arr1[i], arr2[j]].join('/');
result.push(combination);
}
}
return result;
};
/**
* @desc 校验手机号规格 86大陆、853,852香港澳门
* */
export const checkTelPhone = (areaCode, mobile) => {
console.log(areaCode, mobile);
if (!areaCode || typeof areaCode === 'object') return false;
if (!mobile || typeof mobile === 'object') return false;
var preg = '';
switch (areaCode) {
case '86':
preg = /^1[3-9][0-9]{9}$/;
break;
case '853':
preg = /^6[0-9]{7}$/;
break;
case '852':
preg = /^[9|8|7|6|5|4][0-9]{7}$/;
break;
default:
preg = /^[0-9]{7,11}$/;
break;
}
if (!preg.test(mobile)) {
return false;
}
return true;
};
/**
* @desc 检查证电子邮件是否合法
*/
export const checkEmail = (userEmail) => {
if (userEmail == '' || userEmail == null) {
return false;
}
// @符号前面的部分可以包含字母、数字、下划线、减号、点号、百分号、连接符(_、-),要求没有特殊字符。@符号后面的部分必须为字母、数字、点(.)组成的域名,顶级域名至少两个字符,最多为6个字符。
var mailreg = /^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}(\.[a-zA-Z]{2,6})?)$/;
// var mailreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
if (!mailreg.test(userEmail)) {
return false;
}
return true;
};
/**
* 防抖函数
* @param {Function} fn 需要防抖的函数
* @param {number} delay 间隔时间
* @param {boolean} immediate 是否立即执行
* @returns {number} delay
*/
export function debounce(fn, delay, immediate = false) {
// 1.定义一个定时器, 保存上一次的定时器
let timer = null;
let isInvoke = false; // 是否激活了立即执行
// 2.真正执行的函数
const _debounce = function(...args) {
// 取消上一次的定时器
if (timer) clearTimeout(timer);
// 判断是否需要立即执行
if (immediate && !isInvoke) {
fn.apply(this, args);
isInvoke = true; // 已经立即执行, 阻止下次触发的立即执行
} else {
// 延迟执行
timer = setTimeout(() => {
// 外部传入的真正要执行的函数
fn.apply(this, args);
isInvoke = false; // 将isInvoke初始化
}, delay);
}
};
// 封装取消功能
_debounce.cancel = function() {
if (timer) clearTimeout(timer);
timer = null;
isInvoke = false;
};
return _debounce;
}
/**
* @description 节流
* @param { Number } interval ms
* @param { Boolean } [immediate=false] 是否立即执行
*/
export const throttle = (fn, interval, immediate = true) => {
let startTime = 0
const _throttle = function(...args) {
const nowTime = new Date().getTime()
if (!immediate && startTime === 0) {
startTime = nowTime
}
const waitTime = interval - (nowTime - startTime)
if (waitTime <= 0) {
fn.apply(this, args)
startTime = nowTime
}
}
return _throttle
}
export const paylogo = [{
platform: 'wx',
logo: '/static/icon/wxpay.png',
leftImg: 'https://static.panyou.com/assets/miniWeb/weixin.png',
},
{
platform: 'cnwx',
logo: '/static/icon/wxpay.png',
leftImg: 'https://static.panyou.com/assets/miniWeb/weixin.png',
},
{
platform: 'zfb',
logo: '/static/icon/zfbpay.png',
leftImg: 'https://static.panyou.com/assets/miniWeb/zhifubao.png',
},
{
platform: 'baidu',
logo: '/static/icon/zfbpay.png',
leftImg: 'https://static.panyou.com/assets/miniWeb/zhifubao.png',
},
{
platform: 'hkzfb',
logo: '/static/icon/zfbpay.png',
leftImg: 'https://static.panyou.com/assets/miniWeb/zhifubao.png',
},
{
platform: 'xyk',
logo: '/static/icon/visapay.png',
leftImg: '',
},
];
export const areaCodeOptions = [{
value: '86',
label: '+86',
},
{
value: '852',
label: '+852',
},
{
value: '853',
label: '+853',
},
{
value: '886',
label: '+886',
},
{
value: '65',
label: '+65',
},
{
value: '60',
label: '+60',
},
];
export const sex = [{
label: '男',
name: '1',
},
{
label: '女',
name: '2',
},
];
export const platformMap = [{
map: 'mp-weixin',
key: 'wx',
},
{
map: 'mp-alipay',
key: 'zfb',
},
{
map: 'mp-baidu',
key: 'baidu',
},
{
map: 'web',
key: 'h5',
},
{
map: 'android',
key: 'androidApp',
},
{
map: 'ios',
key: 'iosApp',
},
];
export const operaMineList = [{
// icon: '/static/icon/kefu.svg',
note: '點擊聯系線上客服',
path: '/pages/customer/index',
badge: {},
},
{
// icon: '/static/icon/feedback.svg',
note: '意見反饋',
path: '/pages/feedback/index',
badge: {},
},
{
// icon: '/static/icon/shezhi.svg',
note: '設置',
path: '/pages/setting/index',
badge: {},
},
];
export const customerList = [{
name: '點擊聯系線上客服',
type: 'contact',
// icon: '/static/icon/kefu.svg',
value: '',
},
{
name: '港澳:00852-21210200',
type: 'phone',
// icon: '/static/icon/telephone.svg',
value: '00852-21210200',
},
{
name: '國內:4008-652-651',
type: 'phone',
// icon: '/static/icon/telephone.svg',
value: '4008-652-651',
},
];
export const createIdSelector = (id, type = 'single') => {
return new Promise((resolve) => {
const query = uni.createSelectorQuery();
query
.select(id)
.boundingClientRect()
.exec(([res]) => {
resolve(res);
});
});
};
/**
* @description: 封装toast
* @param {*} title
* @param {*} icon
* @param {*} duration
* @return {*}
* @author: ljx
*/
export const showToast = (title, icon = 'none', duration = 2000) => {
uni.showToast({
title,
icon,
duration,
});
};
export const showLoadingToast = () => {
return uni.showLoading({
mask: true,
});
};
export const closeToast = () => {
uni.hideToast();
uni.hideLoading();
};
/**
* 拨打电话
*/
export const telPhone = (phoneNumber) => {
let phone = '';
phoneNumber.split(' ').map((item, index) => {
if (index != 0) {
phone += item;
}
});
uni.makePhoneCall({
phoneNumber: phone,
});
};
/**
* 地图导航
*/
export const toMap = (l, r, n, a) => {
uni.openLocation({
latitude: Number(l),
longitude: Number(r),
name: n,
address: a ? a : '',
success: () => {},
});
};