1.校验
/** * Created by jiachenpan on 16/11/18. */export function validUsername(str) { const valid_map = ["admin", "editor"]; return valid_map.indexOf(str.trim()) >= 0;}/** * 邮箱 * @param {*} s */export function validEmail(s) { return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(s);}/** * 手机号码 * @param {*} s */export function validMobile(s) { return /^1[0-9]{10}$/.test(s);}/** * 电话号码 * @param {*} s */export function validPhone(s) { return /^([0-9]{3,4}-)?[0-9]{7,8}$/.test(s);}/** * URL地址 * @param {*} s */export function validURL(s) { const urlRegex = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/; return urlRegex.test(s);}/* 小写字母*/export function validateLowerCase(str) { const reg = /^[a-z]+$/; return reg.test(str);}/* 大写字母*/export function validateUpperCase(str) { const reg = /^[A-Z]+$/; return reg.test(str);}/* 大小写字母*/export function validateAlphabets(str) { const reg = /^[A-Za-z]+$/; return reg.test(str);}/*验证pad还是pc*/export const validatePc = function () { const userAgentInfo = navigator.userAgent; const Agents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"]; let flag = true; for (let v = 0; v < Agents.length; v++) { if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false; break; } } return flag;};/** * validate email * @param email * @returns {boolean} */export function validateEmail(email) { const re = /^(([^<>()\\[\]\\.,;:\s@"]+(\.[^<>()\\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email);}/** * 判断身份证号码 */export function validateCardId(code) { let list = []; let result = true; let msg = ""; let city = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外 ", }; if (!validateNull(code)) { if (code.length === 18) { if (!code || !/(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(code)) { msg = "证件号码格式错误"; } else if (!city[code.substr(0, 2)]) { msg = "地址编码错误"; } else { //18位身份证需要验证最后一位校验位 code = code.split(""); //∑(ai×Wi)(mod 11) //加权因子 let factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; //校验位 let parity = [1, 0, "X", 9, 8, 7, 6, 5, 4, 3, 2, "x"]; let sum = 0; let ai = 0; let wi = 0; for (let i = 0; i < 17; i++) { ai = code[i]; wi = factor[i]; sum += ai * wi; } if (parity[sum % 11] !== code[17]) { msg = "证件号码校验位错误"; } else { result = false; } } } else { msg = "证件号码长度不为18位"; } } else { msg = "证件号码不能为空"; } list.push(result); list.push(msg); return list;}/** * 判断手机号码是否正确 */export function validateMobile(phone) { let list = []; let result = true; let msg = ""; let isPhone = /^0\d{2,3}-?\d{7,8}$/; //增加134 减少|1349[0-9]{7},增加181,增加145,增加17[678] if (!validateNull(phone)) { if (phone.length === 11) { if (isPhone.test(phone)) { msg = "手机号码格式不正确"; } else { result = false; } } else { msg = "手机号码长度不为11位"; } } else { msg = "手机号码不能为空"; } list.push(result); list.push(msg); return list;}/** * 判断姓名是否正确 */export function validateName(name) { let regName = /^[\u4e00-\u9fa5]{2,4}$/; return regName.test(name);}/** * 判断是否为整数 */export function validateInteger(num, type) { let regName = /[^\d.]/g; if (type === 1) { if (!regName.test(num)) return false; } else if (type === 2) { regName = /[^\d]/g; if (!regName.test(num)) return false; } return true;}/** * 判断是否为小数 */export function validateDecimal(num, type) { let regName = /[^\d.]/g; if (type === 1) { if (!regName.test(num)) return false; } else if (type === 2) { regName = /[^\d.]/g; if (!regName.test(num)) return false; } return true;}/** * 判断是否为空 */export function validateNull(val) { if (typeof val == "boolean") { return false; } if (typeof val == "number") { return false; } if (val instanceof Array) { if (val.length === 0) return true; } else if (val instanceof Object) { if (JSON.stringify(val) === "{}") return true; } else { return val === "null" || val == null || val === "undefined" || val === undefined || val === ""; } return false;}/** * 验证是否存在true/false */export const validateData = (val, defaultVal) => { if (typeof val === "boolean") { return val; } return !validateNull(val) ? val : defaultVal;};
2.日期格式化
// 获取当前日期前一天的日期export function getBeforeDate() { let date = new Date(); date.setTime(date.getTime() - 24 * 60 * 60 * 1000); // 将data格式化yyyy-MM-dd let y = date.getFullYear(); let m = date.getMonth() + 1; let d = date.getDate(); m = m < 10 ? "0" + m : m; d = d < 10 ? "0" + d : d; return y + "-" + m + "-" + d;}export const calcDate = (date1, date2) => { let date3 = date2 - date1; let days = Math.floor(date3 / (24 * 3600 * 1000)); let leave1 = date3 % (24 * 3600 * 1000); //计算天数后剩余的毫秒数 let hours = Math.floor(leave1 / (3600 * 1000)); let leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数 let minutes = Math.floor(leave2 / (60 * 1000)); let leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数 let seconds = Math.round(date3 / 1000); return { leave1, leave2, leave3, days: days, hours: hours, minutes: minutes, seconds: seconds, };};/** * 日期格式化 */export function dateFormat(date) { let format = "yyyy-MM-dd hh:mm:ss"; if (date !== "Invalid Date") { let o = { "M+": date.getMonth() + 1, //month "d+": date.getDate(), //day "h+": date.getHours(), //hour "m+": date.getMinutes(), //minute "s+": date.getSeconds(), //second "q+": Math.floor((date.getMonth() + 3) / 3), //quarter S: date.getMilliseconds(), //millisecond }; if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length)); for (let k in o) if (new RegExp("(" + k + ")").test(format)) format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); return format; } return "";}
3.文件导出
export const exportFile = (result) => { console.log("result", result); let contentDisposition = result.headers["content-disposition"]; // 这里后端给的内容中,文件名字可能是驼峰式名称的 fileName ,或者是全部小写的 filename let filename = decodeURI(contentDisposition.split("fileName=")[1] || contentDisposition.split("filename=")[1]); // let filename = "1.xlsx"; // 注意这里的 result.data ,如果只传 result 的话,最后下载出来的excel文件,里面显示的是 [object Object] let blob = new Blob([result.data], { type: result.headers["content-type"] }); // let blob = new Blob([result.data],{type: "application/x-msdownload;charset=GBK"}); // let blob = new Blob([result.data],{type: "application/x-msdownload"}); // let blob = new Blob([result.data]); // let blob = new Blob([result.data],{type: "application/vnd.ms-excel"}); let url = window.URL.createObjectURL(blob); if (window.navigator.msSaveBlob) { //IE try { window.navigator.msSaveBlob(blob, filename); } catch (e) { console.log(e); } } else { //非IE let link = document.createElement("a"); link.style.display = "none"; link.href = url; link.setAttribute("download", filename); document.body.appendChild(link); link.click(); } URL.revokeObjectURL(url); // 释放内存};
4.公用工具类型
/** * 通用工具类 */export default class func { /** * 不为空 * @param val * @returns {boolean} */ static notEmpty(val) { return !this.isEmpty(val); } /** * 是否为定义 * @param val * @returns {boolean} */ static isUndefined(val) { return val === null || typeof val === "undefined"; } /** * 为空 * @param val * @returns {boolean} */ static isEmpty(val) { return val === null || typeof val === "undefined" || (typeof val === "string" && val === "" && val !== "undefined"); } /** * 强转int型 * @param val * @param defaultValue * @returns {number} */ static toInt(val, defaultValue) { if (this.isEmpty(val)) { return defaultValue === undefined ? -1 : defaultValue; } const num = parseInt(val, 0); return Number.isNaN(num) ? (defaultValue === undefined ? -1 : defaultValue) : num; } /** * Json强转为Form类型 * @param obj * @returns {FormData} */ static toFormData(obj) { const data = new FormData(); Object.keys(obj).forEach((key) => { data.append(key, Array.isArray(obj[key]) ? obj[key].join(",") : obj[key]); }); return data; } /** * date类转为字符串格式 * @param date * @param format * @returns {null} */ static format(date, format = "YYYY-MM-DD HH:mm:ss") { return date ? date.format(format) : null; } /** * 根据逗号联合 * @param arr * @returns {string} */ static join(arr) { return arr ? arr.join(",") : ""; } /** * 根据逗号分隔 * @param str * @returns {string} */ static split(str) { return str ? String(str).split(",") : ""; }}
5.校验规则常量
// 校验规则常量export default { // 手机号码 phone: /^134[0-8]\d{7}$|^13[^4]\d{8}$|^14[5-9]\d{8}$|^15[^4]\d{8}$|^16[6]\d{8}$|^17[0-8]\d{8}$|^18[\d]{9}$|^19[8,9]\d{8}$/, //数字 number: /^\d+$/, //数字,不包含0 noZeroNumber: /^[1-9]\d{0,}$/, // 固定电话 telephone: /(^\d{0,9}-\d{0,10}$)|(^\d{1,20}$)/, //仅中文或英文,不允许含有数字 noNumber: /^[a-zA-Z\u4E00-\u9FA5]*$/, //不允许含有特殊字符 noChar: /^[0-9a-zA-Z\u4E00-\u9FA5]*$/, //邮箱 email: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, //不允许输入中文 noChinese: /^[^\u4e00-\u9fa5]{1,20}$/, //密码为6-16位字母或数字密码 password: /^[0-9a-zA-Z]{6,16}$/, //仅中文 onlineCH: /^[\u4E00-\u9FA5]*$/, // 身份证号 cardNo: /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/,};
6.自定义校验规则
/** * @description:自定义校验规则 * @author: * @date:Created in 2021/12/22 16:20 * @modified By: * @version: 1.0.0 */const { validUpper } = require("@/utils/validate");// 只能输入大写字母与下划线export const tableCodeValidUpper = (rule, val, callback) => { if (val != null && val != "") { const value = val.replace(/^\s*|\s*$/g, ""); if (!validUpper(value)) { callback(new Error("只能输入大写字母与下划线")); } else { callback(); } } else { callback(); }};// 只能输入中文export const tableNameValidUpper = (rule, val, callback) => { if (val != null && val != "") { const value = val.replace(/^\s*|\s*$/g, ""); if (!/^[\u4E00-\u9FA5]*$/.test(value)) { callback(new Error("只能输入中文")); } else { callback(); } } else { callback(); }};// 不允许输入特殊字符export const remarkValidUpper = (rule, val, callback) => { if (val != null && val != "") { const value = val.replace(/^\s*|\s*$/g, ""); if (!/^[0-9a-zA-Z\u4E00-\u9FA5]*$/.test(value)) { callback(new Error("不允许输入特殊字符")); } else { callback(); } } else { callback(); }};// 只能输入数字export const numberValidUpper = (rule, val, callback) => { console.log("val====>", val); if (val != null && val != "") { if (Number(val)) { if (!/^\d+$/.test(val)) { callback(new Error("只能输入数字")); } else { callback(); } } else { callback(); } }};// 只能输入数字和foreverexport const foreverValidUpper = (rule, val, callback) => { const value = val.replace(/^\s*|\s*$/g, ""); if (val != null && val != "") { if (value === "forever") { callback(); } else { if (!/^\d+$/.test(value)) { callback(new Error("只能输入forever和数字")); } else { callback(); } } } else { callback(); }};// 只能输入数字和Englishexport const englishValidUpper = (rule, val, callback) => { if (val != null && val != "") { if (!/^[A-Za-z0-9]+$/.test(val)) { callback(new Error("只能输入数字和英文")); } else { callback(); } } else { callback(); }};// 只能输入数字,且位数只能在16个export const numberValidUppers = (rule, val, callback) => { console.log("val====>", val); if (val != null && val != "") { if (Number(val)) { if (!/^\d{0,16}$/g.test(val)) { callback(new Error("只能输入数字")); } else { callback(); } } else { callback(); } }};---------------------------------校验使用-------------------------------------------------------------describe: [ { required: true, message: "请输入需求描述", trigger: "blur" }, { validator: remarkValidUpper, trigger: "blur" }, //特殊字符校验 ], //需求描述
7.时间日期格式化
/** * @description: 将时间转换为2020/1/1 * @param {String} timestamp 需要转换的时间 * @return {String} t 转换后的时间 */export const formatTs = function (timestamp) { const t = new Date(timestamp).toLocaleDateString(); return t;};/** * @description: 与当前时间的时间差 * @param {String} date 需要转换的时间 * @return {String} 时间差 */export const formatTimestamp = function (date) { const t = new Date(date).toLocaleDateString(); const timestamp = new Date(t); const currentTime = new Date(); return currentTime - timestamp;};/** * @description: 返回当前月和最后一天 * @param {String} timeSecond 需要转换的时间例如:"2020-1-1" * @return {Array} ["2020-01-01", "2020-01-31", "2020-01"] */export const getDateRange = function (timeSecond) { const timeDifference = formatTimestamp(timeSecond); const time = new Date(timeSecond); const year = time.getFullYear(); let month = time.getMonth() + 1; const month2 = month; let day = timeDifference >= 30 * 24 * 3600 * 1000 ? time.getDate() : new Date(new Date()).getDate(); if (month < 10) { month = `0${month}`; } if (day < 10) { day = `0${day}`; } const day31 = [1, 3, 5, 7, 8, 10, 12]; let timeStart = null; let timeEnd = null; const yearMonth = `${year}-${month}`; // 获取当前的时间 if (timeDifference >= 30 * 24 * 3600 * 1000) { timeStart = `${year}-${month}-${day}`; for (let i = 0; i < day31.length; i++) { if (day31[i] === month2) { timeEnd = `${year}-${month}-${31}`; break; } else if (month2 === 2) { timeEnd = `${year}-${month}-${28}`; } else { timeEnd = `${year}-${month}-${30}`; } } } else { timeStart = `${year}-${month}-${"01"}`; timeEnd = `${year}-${month}-${day}`; } return [timeStart, timeEnd, yearMonth];};/** * @description: 当前系统日期 yyyy-MM-dd * @param {String} date 需要转换的时间例如:"2020-1-1" * @return {String} "2020-01-01" */export const getYearMonthDay = function (date) { const d = new Date(date); const yyyy = d.getFullYear(); let MM = d.getMonth() + 1; MM = MM < 10 ? `0${MM}` : MM; let dd = d.getDate(); dd = dd < 10 ? `0${dd}` : dd; return `${yyyy}-${MM}-${dd}`;};/** * @description: 格式 年-月 * @param {String} date 需要转换的时间例如:"2020-1-1" * @return {String} 年月 */export const getYearMonth = function (date) { const d = new Date(date); const datetime = d.getFullYear() + "-" + (d.getMonth() + 1); return datetime;};/** * @description: 格式 时间到时分秒 * @param {String} date 需要转换的时间例如:"2020-1-1" * @return {String} 年月日时分秒 */export const format = function (date) { if (!date) return; var date2 = new Date(date); var y = date2.getFullYear(); var m = date2.getMonth() + 1; m = m < 10 ? "0" + m : m; var d = date2.getDate(); d = d < 10 ? "0" + d : d; var h = date2.getHours(); h = h < 10 ? "0" + h : h; var minute = date2.getMinutes(); minute = minute < 10 ? "0" + minute : minute; var seconds = date2.getSeconds(); seconds = seconds < 10 ? "0" + seconds : seconds; return y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + seconds;};/** * @description: 格式 处理时间到时 * @param {String} date 需要转换的时间 * @param {String} h 不足两位补两位 * @return {String} 年月日时 */export const todayTime = function (date, h) { var date2 = new Date(date); var y = date2.getFullYear(); var m = date2.getMonth() + 1; m = m < 10 ? "0" + m : m; var d = date2.getDate(); d = d < 10 ? "0" + d : d; h = h < 10 ? "0" + h : h; return y + "-" + m + "-" + d + " " + h + ":" + "00" + ":" + "00";};/** * @description: 格式 处理时间到年月日 * @param {String} date 需要转换的时间 * @return {String} 年月日 */export const todayTime1 = function (date) { var date2 = new Date(date); var y = date2.getFullYear(); var m = date2.getMonth() + 1; m = m < 10 ? "0" + m : m; var d = date2.getDate(); d = d < 10 ? "0" + d : d; return y + "-" + m + "-" + d + " " + "00" + ":" + "00" + ":" + "00";};/** * @description: 格式 获取是分秒 * @param {String} date 需要转换的时间 * @param {String} type 转换类型 * @return {String} 时分/时分秒 */export const formatTime = function (date, type) { if (!date) return; var h = date.getHours(); h = h < 10 ? "0" + h : h; var minute = date.getMinutes(); minute = minute < 10 ? "0" + minute : minute; var seconds = date.getSeconds(); seconds = seconds < 10 ? "0" + seconds : seconds; if (type === "HH:mm") { return h + ":" + minute; } return h + ":" + minute + ":" + seconds;};/** * @description: 格式 获取周几 * @param {String} date 需要转换的时间 * @return {String} 星期几 */export const formatDay = function (date) { if (!date) return; var days = date.getDay(); switch (days) { case 1: days = "星期一"; break; case 2: days = "星期二"; break; case 3: days = "星期三"; break; case 4: days = "星期四"; break; case 5: days = "星期五"; break; case 6: days = "星期六"; break; case 0: days = "星期日"; break; } return days;};/** * @description: 转换时间戳年月日 * @param {String} str 需要转换的时间 * @return {String} 时间戳 */export const getLocalTimes = (str) => { if (!str || str === null || str === "") { return str; } var tf = function (i) { return (i < 10 ? "0" : "") + i; }; var oDate = new Date(str); var oYear = oDate.getFullYear() + "-"; var oMonth = (oDate.getMonth() + 1 < 10 ? "0" + (oDate.getMonth() + 1) : oDate.getMonth() + 1) + "-"; var oDay = tf(oDate.getDate()) + " "; return oYear + oMonth + oDay;};/** * @description 获取当前时间的年月日信息星期几的信息 * @param date * @return {{month: number, year: number, days: number, day: number}} */export const getNewDate = (date) => { let year = date.getFullYear(); let month = date.getMonth(); let day = date.getDate(); let days = date.getDay(); return { year, month, day, days };};/** * @description获取一个月份的所有天数 * @param year 年份 * @param month 月份 * @return {[]} 一个月所有天数的数组 */export const getMonthList = (year, month) => { let d = new Date(year, month, 0).getDate(); // 获取某一个月的天数 let list = []; for (let j = 0; j < d; j++) { list.push(month + "-" + (j + 1)); } return list;};/** * 返回每个月的开始时候和结束时间,或者一年的开始时间和结束时间 * @param date 时间对象 * @param status 1:月,2:年 * @param flag 0:开始时间,1:结束时间 * @returns {string} 返回时间字符串格式 xxxx-xx-xx xx:xx:xx */export const getYearOrMonthFirstTime = (date, status, flag) => { let year = date.getFullYear(); let month = date.getMonth(); if (status === 1) { if (flag === 0) { month = month + 1; return year + "-" + (month < 10 ? `0${month}` : month) + "-01 00:00:00"; } else { let day = new Date(year, month, 0); month = month + 1; return year + "-" + (month < 10 ? `0${month}` : month) + "-" + day.getDate() + " 23:59:59"; } } else { if (flag === 0) { return year + "-" + "01" + "-01 00:00:00"; } else { return year + "-" + "12" + "-31 23:59:59"; } }};/** * @description 根据当前时间获取上个月的时间 * @param date 传入的时间 * @return {string} 返回时间字符串格式 xxxx-xx-xx xx:xx:xx */export const getLastMouthDate = (date) => { let year = date.getFullYear(); let month = date.getMonth(); let dateTime = new Date(year, month - 1, 1); return format(dateTime);};/** * @description 获取当前月的第一天 * @param date 日期时间 * @return {string} 返回xxxx-xx-xx格式的字符串时间 */export const getMouthFirstDay = (date) => { const d = new Date(date); const yyyy = d.getFullYear(); let MM = d.getMonth() + 1; MM = MM < 10 ? `0${MM}` : MM; return `${yyyy}-${MM}-01`;};/** * Parse the time to string * @param {(Object|string|number)} time * @param {string} cFormat * @returns {string | null} */export function parseTime(time, cFormat) { if (arguments.length === 0) { return null; } const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}"; let date; if (typeof time === "object") { date = time; } else { if (typeof time === "string" && /^[0-9]+$/.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 ["日", "一", "二", "三", "四", "五", "六"][value]; } return value.toString().padStart(2, "0"); }); return time_str;}
8.单位转换为字节
/** * 文件大小 字节转换单位 * @param size * @returns {string|*} * @name:王浩 */export const filterSize = (size) => { if (!size) return ""; if (size < pow1024(1)) return size + " B"; if (size < pow1024(2)) return (size / pow1024(1)).toFixed(2) + " KB"; if (size < pow1024(3)) return (size / pow1024(2)).toFixed(2) + " MB"; if (size < pow1024(4)) return (size / pow1024(3)).toFixed(2) + " GB"; return (size / pow1024(4)).toFixed(2) + " TB";};// 求次幂function pow1024(num) { return Math.pow(1024, num);}/** * @name:王浩 * @description: 当前系统日期 yyyy-MM-dd * @param {String} date 需要转换的时间例如:"2020-1-1" * @return {String} "2020-01-01" */export const getYearMonthDay = function (date) { const d = new Date(date); const yyyy = d.getFullYear(); let MM = d.getMonth() + 1; MM = MM < 10 ? `0${MM}` : MM; let dd = d.getDate(); dd = dd < 10 ? `0${dd}` : dd; return `${yyyy}-${MM}-${dd}`;};/** * @description: 格式 时间到时分秒 * @param {String} date 需要转换的时间例如:"2020-1-1" * @return {String} 年月日时分秒 */export const format = function (date) { if (!date) return; var date2 = new Date(date); var y = date2.getFullYear(); var m = date2.getMonth() + 1; m = m < 10 ? "0" + m : m; var d = date2.getDate(); d = d < 10 ? "0" + d : d; var h = date2.getHours(); h = h < 10 ? "0" + h : h; var minute = date2.getMinutes(); minute = minute < 10 ? "0" + minute : minute; var seconds = date2.getSeconds(); seconds = seconds < 10 ? "0" + seconds : seconds; return y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + seconds;};
9.根据文件类型判断不同的图片
/** * @description:根据文件类型判断不同的图片 * @author: * @date:Created in 2022/1/12 16:20 * @modified By:王浩 * @version: 1.0.0 *///匹配文件后缀export function matchFileSuffixType(fileName) { // 后缀获取 var suffix = ""; // 获取类型结果 var result = ""; try { var flieArr = fileName.split("."); suffix = flieArr[flieArr.length - 1]; } catch (err) { suffix = ""; } // fileName无后缀返回 false if (!suffix) { result = false; return result; } // 图片格式 var imglist = ["png", "jpg", "jpeg", "bmp", "gif", "tif", "tiff"]; // 进行图片匹配 result = imglist.some(function (item) { return item == suffix; }); if (result) { result = "image"; return result; } // 匹配txt var txtlist = ["txt"]; result = txtlist.some(function (item) { return item == suffix; }); if (result) { result = "txt"; return result; } // 匹配 doc文件 var officelist = ["doc", "docx"]; result = officelist.some(function (item) { return item == suffix; }); if (result) { result = "doc"; return result; } // -----------pdf--------------- var pdf = ["pdf"]; result = pdf.some(function (item) { return item == suffix; }); if (result) { result = "pdf"; return result; } // 匹配xlsx文件类型 var download = ["xlsx", "xls"]; result = download.some(function (item) { return item == suffix; }); if (result) { result = "xls"; return result; } // 匹配压缩文件 var ziplist = ["zip", "rar", "jar", "tar", "gzip"]; result = ziplist.some(function (item) { return item == suffix; }); if (result) { result = "zip"; return result; } // 匹配 视频 var videolist = ["mp4", "m2v", "mkv"]; result = videolist.some(function (item) { return item == suffix; }); if (result) { result = "video"; return result; } // 匹配 音频 var radiolist = ["mp3", "wav", "wmv"]; result = radiolist.some(function (item) { return item == suffix; }); if (result) { result = "radio"; return result; } // 其他 文件类型 result = "other"; return result;}
10.其他方法
export const forEach = (arr, fn) => { if (!arr.length || !fn) return; let i = -1; let len = arr.length; while (++i < len) { let item = arr[i]; fn(item, i, arr); }};/** * @param {Array} arr1 * @param {Array} arr2 * @description 得到两个数组的交集, 两个数组的元素为数值或字符串 */export const getIntersection = (arr1, arr2) => { let len = Math.min(arr1.length, arr2.length); let i = -1; let res = []; while (++i < len) { const item = arr2[i]; if (arr1.indexOf(item) > -1) res.push(item); } return res;};/** * @param {Array} arr1 * @param {Array} arr2 * @description 得到两个数组的并集, 两个数组的元素为数值或字符串 */export const getUnion = (arr1, arr2) => { return Array.from(new Set([...arr1, ...arr2]));};/** * @param {Array} target 目标数组 * @param {Array} arr 需要查询的数组 * @description 判断要查询的数组是否至少有一个元素包含在目标数组中 */export const hasOneOf = (targetarr, arr) => { return targetarr.some((_) => arr.indexOf(_) > -1);};/** * @param {String|Number} value 要验证的字符串或数值 * @param {*} validList 用来验证的列表 */export function oneOf(value, validList) { for (let i = 0; i < validList.length; i++) { if (value === validList[i]) { return true; } } return false;}/** * @param {Number} timeStamp 判断时间戳格式是否是毫秒 * @returns {Boolean} */const isMillisecond = (timeStamp) => { const timeStr = String(timeStamp); return timeStr.length > 10;};/** * @param {Number} timeStamp 传入的时间戳 * @param {Number} currentTime 当前时间时间戳 * @returns {Boolean} 传入的时间戳是否早于当前时间戳 */const isEarly = (timeStamp, currentTime) => { return timeStamp < currentTime;};/** * @param {Number} num 数值 * @returns {String} 处理后的字符串 * @description 如果传入的数值小于10,即位数只有1位,则在前面补充0 */const getHandledValue = (num) => { return num < 10 ? "0" + num : num;};/** * @param {Number} timeStamp 传入的时间戳 * @param {Number} startType 要返回的时间字符串的格式类型,传入'year'则返回年开头的完整时间 */const getDate = (timeStamp, startType) => { const d = new Date(timeStamp * 1000); const year = d.getFullYear(); const month = getHandledValue(d.getMonth() + 1); const date = getHandledValue(d.getDate()); const hours = getHandledValue(d.getHours()); const minutes = getHandledValue(d.getMinutes()); const second = getHandledValue(d.getSeconds()); let resStr = ""; if (startType === "year") resStr = year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + second; else resStr = month + "-" + date + " " + hours + ":" + minutes; return resStr;};/** * @param {String|Number} timeStamp 时间戳 * @returns {String} 相对时间字符串 */export const getRelativeTime = (timeStamp) => { // 判断当前传入的时间戳是秒格式还是毫秒 const IS_MILLISECOND = isMillisecond(timeStamp); // 如果是毫秒格式则转为秒格式 if (IS_MILLISECOND) Math.floor((timeStamp /= 1000)); // 传入的时间戳可以是数值或字符串类型,这里统一转为数值类型 timeStamp = Number(timeStamp); // 获取当前时间时间戳 const currentTime = Math.floor(Date.parse(new Date()) / 1000); // 判断传入时间戳是否早于当前时间戳 const IS_EARLY = isEarly(timeStamp, currentTime); // 获取两个时间戳差值 let diff = currentTime - timeStamp; // 如果IS_EARLY为false则差值取反 if (!IS_EARLY) diff = -diff; let resStr = ""; const dirStr = IS_EARLY ? "前" : "后"; // 少于等于59秒 if (diff <= 59) resStr = diff + "秒" + dirStr; // 多于59秒,少于等于59分钟59秒 else if (diff > 59 && diff <= 3599) resStr = Math.floor(diff / 60) + "分钟" + dirStr; // 多于59分钟59秒,少于等于23小时59分钟59秒 else if (diff > 3599 && diff <= 86399) resStr = Math.floor(diff / 3600) + "小时" + dirStr; // 多于23小时59分钟59秒,少于等于29天59分钟59秒 else if (diff > 86399 && diff <= 2623859) resStr = Math.floor(diff / 86400) + "天" + dirStr; // 多于29天59分钟59秒,少于364天23小时59分钟59秒,且传入的时间戳早于当前 else if (diff > 2623859 && diff <= 31567859 && IS_EARLY) resStr = getDate(timeStamp); else resStr = getDate(timeStamp, "year"); return resStr;};/** * @returns {String} 当前浏览器名称 */export const getExplorer = () => { const ua = window.navigator.userAgent; const isExplorer = (exp) => { return ua.indexOf(exp) > -1; }; if (isExplorer("MSIE")) return "IE"; else if (isExplorer("Firefox")) return "Firefox"; else if (isExplorer("Chrome")) return "Chrome"; else if (isExplorer("Opera")) return "Opera"; else if (isExplorer("Safari")) return "Safari";};/** * @description 绑定事件 on(element, event, handler) */export const on = (function () { if (document.addEventListener) { return function (element, event, handler) { if (element && event && handler) { element.addEventListener(event, handler, false); } }; } else { return function (element, event, handler) { if (element && event && handler) { element.attachEvent("on" + event, handler); } }; }})();/** * @description 解绑事件 off(element, event, handler) */export const off = (function () { if (document.removeEventListener) { return function (element, event, handler) { if (element && event) { element.removeEventListener(event, handler, false); } }; } else { return function (element, event, handler) { if (element && event) { element.detachEvent("on" + event, handler); } }; }})();/** * 判断一个对象是否存在key,如果传入第二个参数key,则是判断这个obj对象是否存在key这个属性 * 如果没有传入key这个参数,则判断obj对象是否有键值对 */export const hasKey = (obj, key) => { if (key) return key in obj; else { let keysArr = Object.keys(obj); return keysArr.length; }};/** * @param {*} obj1 对象 * @param {*} obj2 对象 * @description 判断两个对象是否相等,这两个对象的值只能是数字或字符串 */export const objEqual = (obj1, obj2) => { const keysArr1 = Object.keys(obj1); const keysArr2 = Object.keys(obj2); if (keysArr1.length !== keysArr2.length) return false; else if (keysArr1.length === 0 && keysArr2.length === 0) return true; /* eslint-disable-next-line */ else return !keysArr1.some((key) => obj1[key] != obj2[key]);};
11.表单序列化 、获取类型 、对象深拷贝 、加密处理
import { validateNull } from "./validate";import * as CryptoJS from "crypto-js";/** * 表单序列化 * @param data * @returns {string} */export const serialize = (data) => { let list = []; Object.keys(data).forEach((ele) => { list.push(`${ele}=${data[ele]}`); }); return list.join("&");};/** * 获取类型 * @param obj * @returns {string|*} */export const getObjType = (obj) => { let toString = Object.prototype.toString; let map = { "[object Boolean]": "boolean", "[object Number]": "number", "[object String]": "string", "[object Function]": "function", "[object Array]": "array", "[object Date]": "date", "[object RegExp]": "regExp", "[object Undefined]": "undefined", "[object Null]": "null", "[object Object]": "object", }; if (obj instanceof Element) { return "element"; } return map[toString.call(obj)];};/** * 对象深拷贝 */export const deepClone = (data) => { let type = getObjType(data); let obj; if (type === "array") { obj = []; } else if (type === "object") { obj = {}; } else { //不再具有下一层次 return data; } if (type === "array") { for (let i = 0, len = data.length; i < len; i++) { obj.push(deepClone(data[i])); } } else if (type === "object") { for (let key in data) { obj[key] = deepClone(data[key]); } } return obj;};/** * 设置主题 */export const setTheme = (name) => { document.body.className = name;};/** * 加密处理 */export const encryption = (params) => { let { data, type, param, key } = params; let result = JSON.parse(JSON.stringify(data)); if (type === "Base64") { param.forEach((ele) => { result[ele] = btoa(result[ele]); }); } else if (type === "Aes") { param.forEach((ele) => { let data = result[ele]; let newKey = CryptoJS.enc.Latin1.parse(key); let iv = newKey; // 加密 let encrypted = CryptoJS.AES.encrypt(data, newKey, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.ZeroPadding, }); result[ele] = encrypted.toString(); }); } return result;};
12.递归寻找子类的父类
/** * 递归寻找子类的父类 */export const findParent = (menu, id) => { for (let i = 0; i < menu.length; i++) { if (menu[i].children.length != 0) { for (let j = 0; j < menu[i].children.length; j++) { if (menu[i].children[j].id == id) { return menu[i]; } else { if (menu[i].children[j].children.length != 0) { return findParent(menu[i].children[j].children, id); } } } } }};
13.判断路由是否相等
/** * 判断路由是否相等 */export const diff = (obj1, obj2) => { delete obj1.close; let o1 = obj1 instanceof Object; let o2 = obj2 instanceof Object; if (!o1 || !o2) { /* 判断不是对象 */ return obj1 === obj2; } if (Object.keys(obj1).length !== Object.keys(obj2).length) { return false; //Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如:数组返回下表:let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2; } for (let attr in obj1) { let t1 = obj1[attr] instanceof Object; let t2 = obj2[attr] instanceof Object; if (t1 && t2) { return diff(obj1[attr], obj2[attr]); } else if (obj1[attr] !== obj2[attr]) { return false; } } return true;};
14.根据字典的value显示label 、 根据字典的value查找对应的index
/** * 根据字典的value显示label */export const findByValue = (dic, value) => { let result; if (validateNull(dic)) return value; if (typeof value == "string" || typeof value == "number" || typeof value == "boolean") { let index = 0; index = findArray(dic, value); if (index !== -1) { result = dic[index].label; } else { result = value; } } else if (value instanceof Array) { result = []; let index = 0; value.forEach((ele) => { index = findArray(dic, ele); if (index !== -1) { result.push(dic[index].label); } else { result.push(value); } }); result = result.toString(); } return result;};/** * 根据字典的value查找对应的index */export const findArray = (dic, value) => { for (let i = 0; i < dic.length; i++) { if (dic[i].value === value) { return i; } } return -1;};
15.打开小窗口
/** * 打开小窗口 */export const openWindow = (url, title, w, h) => { // Fixes dual-screen position Most browsers Firefox const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left; const dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top; const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width; const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height; const left = width / 2 - w / 2 + dualScreenLeft; const top = height / 2 - h / 2 + dualScreenTop; const newWindow = window.open( url, title, "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=" + w + ", height=" + h + ", top=" + top + ", left=" + left, ); // Puts focus on the newWindow if (window.focus) { newWindow.focus(); }};