1、常用工具类
2、本地存储工具类
点击查看更多
常用工具类 tool.js
/*
* 验证手机号是否合格
* true--说明合格
*/
export function isPhone(phoneStr){
let myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
if (!myreg.test(phoneStr)) {
return false;
} else {
return true;
}
}
/*
* 验证身份证号是否合格
* true--说明合格
*/
export function isIdCard(idCardStr) {
let idcardReg = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/
if (idcardReg.test(idCardStr)) {
return true
} else {
return false
}
}
/**
* 验证车牌号是否合格
* true--说明合格
*/
export function isVehicleNumber(vehicleNumber) {
let xreg=/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))/;
let creg=/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/;
if(vehicleNumber.length == 7){
return creg.test(vehicleNumber);
} else if(vehicleNumber.length == 8){
return xreg.test(vehicleNumber);
} else{
return false;
}
}
/*
* 验证字符串是否为空(也不能为纯空格)
* true--说明为空, false--说明不为空
*/
export function isEmptyString(string) {
if (string == undefined
|| typeof string == "undefined"
|| !string
|| string == null
|| string == ''
|| /^\s+$/gi.test(string) ) {
return true;
}else{
return false;
}
}
/*
* 生日转为年龄(精确到月份)
*/
export function birsdayToAge(birsday) {
let aDate = new Date();
let thisYear = aDate.getFullYear();
let bDate = new Date(birsday);
let brith = bDate.getFullYear();
let age = thisYear - brith;
if(aDate.getMonth()==bDate.getMonth()){
if(aDate.getDate()<bDate.getDate()){
age = age -1;
}
}else{
if(aDate.getMonth()<bDate.getMonth()){
age = age -1;
}
}
return age
}
/*
* 是否空数组
*/
export function isArrayEmpty(val) {
if(val && val instanceof Array && val.length>0){
return false;
}else{
return true;
}
}
/*
* 获取url参数字符串
* 没有返回null
*/
export function getQueryString(name) {
let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
let r = window.location.search.substr(1).match(reg)
if (r != null) {
return unescape(r[2])
}
return null
}
/*
* 递归深拷贝
*/
export function deepCopy(obj) {
let result = Array.isArray(obj) ? [] : {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
if(typeof obj[key] === 'object' && obj[key] !== null) {
result[key] = deepCopy(obj[key]);
} else {
result[key] = obj[key];
}
}
}
return result;
}
/**
* 去除参数空数据(用于向后台传递参数的时候)
* @param {Object} obj [参数对象]
*/
export function filterEmptyData(obj){
for (let prop in obj) {
obj[prop] === '' ? delete obj[prop] : obj[prop]
}
return obj;
}
/**
* @desc 函数防抖,用于多次触发,只执行 规定时间后再执行有且只有一次触发 的情况。便于优化性能
* @param {function} func - 需要使用函数防抖的被执行的函数。必传
* @param {Number} wait - 多少毫秒之内触发,只执行第一次,默认1000ms。可以不传
*/
export function debounce(func, wait) {
let timeout = null
wait = wait || 1000
return function() {
let context = this
let args = arguments
if (timeout) clearTimeout(timeout)
let callNow = !timeout
timeout = setTimeout(() => {
timeout = null
}, wait)
if (callNow) func.apply(context, args)
}
}
/**
* 自动生成uuid
* param:{
* len:长度
* radix:进制数 8,10,16
* }
*/
//随机获取id
export function uuId(len, radix) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
var uuid = []
var i = 0
radix = radix || chars.length
if (len) {
for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)]
} else {
var r = 0
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
uuid[14] = '4'
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | (Math.random() * 16)
uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r]
}
}
}
return uuid.join('')
}
/*
生成一个随机数
*/
export function mathRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
/*
数组去重
param:{
arr: 入参数组,
key: 主键
}
*/
export function arrayDuplication(arr, key) {
let json = {}
let arrTemp = []
arr.forEach(item => {
json[item[key]] = item
})
for (let name in json) {
arrTemp.push(json[name])
}
return arrTemp
}
/*
获取多少天后的时间
param:{
today: 时间("2021-7-8"),
addDayCount: 天数
}
*/
export function getDateStr(today, addDayCount) {
var dd
if (today) {
dd = new Date(today)
} else {
dd = new Date()
}
dd.setDate(dd.getDate() + addDayCount) //获取AddDayCount天后的日期
var y = dd.getFullYear()
var m = dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1
var d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate()
return y + '-' + m + '-' + d
},
/* 这个方法不常用,但是很重要!
递归找到所有节点中 id的某一项
param:{
data: 入参数组(tree),
v: id
}
*/
export function getSelfRid(data, v) {
let value = null
for (const item of data) {
if (item.rid === v) {
value = item
break
}
if (item.children) {
const _value = this.getSelfRid(item.children, v)
if (_value) {
return _value
}
}
}
return value
},
/*
获取任一元素的任意属性
*/
function getStyle(elem, prop) {
return window.getComputedStyle
? window.getComputedStyle(elem, null)[prop]
: elem.currentStyle[prop];
}
/*
递归--给每一项新增属性
*/
export function format(arr) {
arr.forEach((el) => {
if (el.children && el.children.length > 0) {
el.value = el.id;
el.label = el.orgName;
this.format(el.children);
} else {
el.value = el.id;
el.label = el.orgName;
}
});
return arr;
},
本地存储工具类
/**
* 设置本地localStorage
* @name {String} 数据对象的KEY
* @data {all} 对应key的数据
*/
export function setStorage(name, data) {
let storage = window.localStorage;
storage.setItem(name, JSON.stringify(data));
}
/**
* 拿到本地localStorage
* @name {String} 数据对象的KEY
*/
export function getStorage(name) {
let storage = window.localStorage;
let data = JSON.parse(storage.getItem(name));
return data;
}
/**
* 设置本地sessionStorage
* @name {String} 数据对象的KEY
* @data {all} 对应key的数据
*/
export function setSessionStorage(name, data) {
let storage = window.sessionStorage;
storage.setItem(name, JSON.stringify(data));
}
/**
* 拿到本地sessionStorage
* @name {String} 数据对象的KEY
*/
export function getSessionStorage(name) {
let storage = window.sessionStorage;
let data = JSON.parse(storage.getItem(name));
return data;
}
// 根据xx的首字母 递增 排序
export function compare(prop) {
return function (obj1, obj2) {
var val1 = obj1[prop];
var val2 = obj2[prop];
if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
val1 = Number(val1);
val2 = Number(val2);
}
if (val1 < val2) {
return -1;
} else if (val1 > val2) {
return 1;
} else {
return 0;
}
}
},
一个数组先按照某个属性的大小排序,如果大小一样的就按照名称排序
let sortBynum_name = (a, b) => {
if(a.status - b.status === 0) {
console.log(a, b)
return a.gridName.localeCompare(b.gridName)
} else {
return a.status - b.status
}
}
this.list = val.sort(sortBynum_name);
鼠标滚轮事件
handle(delta, event) {
if(event.ctrlKey) {
this.$refs.rightWrap.style.width = "calc(100% - " + this.leftWrapWidth + ")"
}
},
addEvent() {
let _this = this
if (window.addEventListener) //FF,火狐浏览器会识别该方法
window.addEventListener('DOMMouseScroll', wheel, false);
window.onmousewheel = document.onmousewheel = wheel; //W3C
//统一处理滚轮滚动事件
function wheel(event) {
var delta = 0;
if (!event) event = window.event;
if (event.wheelDelta) { //IE、chrome浏览器使用的是wheelDelta,并且值为“正负120”
delta = event.wheelDelta / 120;
if (window.opera) delta = -delta; //因为IE、chrome等向下滚动是负值,FF是正值,为了处理一致性,在此取反处理
} else if (event.detail) { //FF浏览器使用的是detail,其值为“正负3”
delta = -event.detail / 3;
}
if (delta)
_this.handle(delta, event);
}
}
Vue 中的错误和警告提供一个全局的自定义处理程序
Vue.config.errorHandler = (err) => {
alert(err);
};
// Vue 3
const app = createApp(App);
app.config.errorHandler = (err) => {
alert(err);
};