这是在vue2项目中使用到的,偶尔同一个方法2和3在写法上会有些区别改动,不然就报错文章来源:https://uudwc.com/A/Pd2bx
import { downFile, postDownFile} from '@/utils/request'
import { MessageBox } from 'element-ui';
/**
* 输入框判空
* @param {*} str
* @returns
*/
export function getText(str) {
return str.replace(/ /gi, '') // 将所有 空格 replace ''
.replace(/<[^<br/>]+>/g, '') // 将所有 换行符 replace ''
}
export function isNull(str) {
if (str == '') return true
var regu = '^[ ]+$'
var re = new RegExp(regu)
return re.test(str)
}
/**
* 判断是否为中文
* @param {*} str
* @returns
*/
export function rulesCN(str) {
let reg=/^[\u4E00-\u9FA5]+$/
if(reg.test(str)) {
// 中文
return true
}else {
return false
}
}
/**
* 判断是否为英文
* @param {*} str
* @returns
*/
export function rulesEN(str) {
let reg=/[^a-zA-Z]/g
if(!reg.test(str)) {
// 英文
return true
}else {
return false
}
}
/**
* 去掉空格
* @param {*} str
* @returns
*/
export function removeTrim(str) {
str = str.replaceAll(' ', '')
return str
}
/**
* 去掉中文和括号()
* @param {*} strValue
* @returns
*/
export function removeChinese(strValue) {
if(strValue!= null && strValue != ""){
var reg = /[\u4e00-\u9fa5]/g;
return strValue.replace(reg, "").replace(/\(|)/g,'')
}
else
return "";
}
/**
* 判空
* @param {*} val
* @returns
*/
export const isEmpty = (val) => {
if(val === '' || val === {} || val === [] || val === null || val === undefined) {
return false
}else {
return true
}
}
/**
* 当前zoom
* @returns
*/
export const zoom = () => {
let zoom = document.getElementsByTagName('body')[0].style.zoom
return zoom
}
/**
* 设置菜单高亮
* @param {class类名} className
* @param {菜单路由} path
*/
export function MenuHighlight(className, path) {
let menuItem = document.getElementsByClassName(className)[0].childNodes
for(let i= 0; i< menuItem.length; i++) {
if(path.indexOf(menuItem[i].dataset.path) > -1) {
menuItem[i].setAttribute('class', 'el-menu-item is-active')
}else {
menuItem[i].setAttribute('class', 'el-menu-item')
}
}
}
/**
* 下载文件
* @param {接口地址} url
* @param {入参} parameter
* @param {文件名} fileName
* @returns
*/
export function downloadFile(url, parameter, fileName) {
return downFile(url, parameter).then((data) => {
if (!data || data.size === 0) { // 如果接口没有返回数据,就提示下载失败
this.$message.warning('存在异常数据,文件导出失败')
return
}
// window.navigator.msSaveBlob是显示保存按钮
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(new Blob([data]), fileName)
return
} else {
let url = window.URL.createObjectURL(new Blob([data]))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click()
document.body.removeChild(link) // 下载完成移除元素
window.URL.revokeObjectURL(url) // 释放掉blob对象
return
}
}).catch(err => {
this.$message.error('存在异常数据,文件导出失败')
})
}
/**
* 将树形结构数据转换为级联要求的字段
* @param tree
* @param map
* @returns
*/
export const converTree = (tree, map = {
label: 'name',
value: 'id',
children: 'children'
}) => {
const result = [];
tree.forEach((item) => {
let value = item[ map.value ];
let label = item[ map.label ];
let children = item[ map.children ];
if (children) {
children = converTree(children, map);
}
result.push({ value, label, children });
})
return result
}
/**
* 将后台数据转换为树形结构
* @param pid
* @param arr
* @returns
*/
export const getTrees = (pid, arr) => {
return arr.filter((item) => item.parentId === pid).map((item) => {
// item.children = getTrees(item.id, arr)
let newArr = getTrees(item.id, arr)
if(Array.isArray(newArr ) && newArr.length>0){
item.children = newArr
}
return item
})
}
/**
* 判断是否文本溢出
* @param e 事件对象
* @returns
*/
export const isBeyond = (e) => {
const ev = window.event || e;
const textRange = (el) => {
const textContent = el
const targetW = textContent.getBoundingClientRect().width
const range = document.createRange()
range.setStart(textContent, 0)
range.setEnd(textContent, textContent.childNodes.length)
const rangeWidth = range.getBoundingClientRect().width
return rangeWidth > targetW
}
return !textRange(ev.target)
}
/**
*
* @param {*} form_key
* @param {*} form_data
*/
export const mapKey = (form_key, form_data ) => {
let form_bk = {}
Object.keys(form_key).forEach(key => {
form_bk[key] = form_data[key]
})
return form_bk
}
// 确认删除提示框
export const confirmDel = (callback) => {
MessageBox.confirm(
'是否确认删除?',
'提示',
{
confirmButtonText: '确认',
cancelButtonText: '取消',
type: 'warning',
}
)
.then(() => {
callback()
})
}
/**
* 高亮表格搜索列
* @param {表格列} tableColumns
* @param {搜索参数} params
* @returns
*/
export const handleHighLight = (tableColumns,params) => {
// 去除其他列的高亮
tableColumns.forEach(item => {
if (item.className?.includes('is-active')) {
let arr = item.className.split(' ')
item.className = arr[0]
}
})
// 高亮当前搜索列
if (params.value !== '') {
tableColumns.forEach(item => {
if (item.className === params.field) {
item.className = params.field + ' ' + 'is-active'
}
})
}
}
/**
* 删除数组中指定对象
* @param {数组} arr
* @param {对象中匹配的key} key
* @returns
*/
export const removeObjWithArr = (arr,key) => {
arr.forEach((item,index,array)=>{
if(item.key === key){
array.splice(index,1)
}
})
}
/**
* 判断数据中是否存在某个对象
* @param {数组} arr
* @param {对象中的key} key
* @param {跟key比对的值} val
* @returns
*/
export const findItem = (arr,key,val) => {
for(let i = 0; i < arr.length; i++) {
if(arr[i][key] == val) {
return i
}
}
return -1
}
/**
* 比对下拉数据
* @param {*} list
* @param {*} type
* @returns
*/
export const compare = (list, type) => {
let cnName = ''
list?.forEach((i) => {
if(i.type === type) {
cnName = i.name
}
})
return cnName
}
/**
* 多维数组去重
* @param {*} list
* @param {*} type
* @returns
*/
export const handleUnique = (arr) => {
// 因对象特别,分出数组中的对象单独去重
let objArr = arr.filter((item) => {
return Object.prototype.toString.call(item) === "[object Object]";
});
let otherTypeArr = arr.filter((item) => {
return Object.prototype.toString.call(item) !== "[object Object]";
});
// 数组及简单类型处理
let obj = {};
otherTypeArr = otherTypeArr.filter((item, index) => {
let newItem = item + JSON.stringify(item);
return obj.hasOwnProperty(newItem) ? false : (obj[newItem] = true);
});
// 对象类型处理
if (objArr.length !== 0) {
// 将数组对象转成数组字符串
var objToStrArr = [];
var keyArr = [];
var key = "";
var currentObj = {};
var currentStr = "";
objArr.forEach(item => {
// 对象属性排序
keyArr = [];
for (key in item) {
keyArr.push(key);
}
keyArr.sort(); // 降序
currentObj = {};
keyArr.forEach(ele => {
currentObj[ele] = item[ele];
})
currentStr = JSON.stringify(currentObj);
// 去除空格及\t空白字符
currentStr = currentStr.replace(/(\s|[\\t])/g, "");
objToStrArr.push(currentStr);
})
objToStrArr.sort();
var tmepArr = [];
// 数组去重
objToStrArr.forEach((item, i) => {
if (item !== tmepArr[tmepArr.length - 1]) {
tmepArr.push(item);
}
})
var resultArr = [];
// 新数组字符串转成数组对象
tmepArr.forEach((item) => {
resultArr.push(JSON.parse(item));
})
objArr = resultArr;
}
return [...otherTypeArr, ...objArr];
}
这是在vue3项目中用到的文章来源地址https://uudwc.com/A/Pd2bx
import router from "@/router/index"
export function pick(obj, arr) {
return arr.reduce(
(iter, val) => (val in obj && (iter[val] = obj[val]), iter),
{}
);
}
/**
* 节流
* @param {function} fn
* @param {number} delay
* @returns {function}
*/
export function throttle(fn, delay) {
let flag = true;
return function () {
// 等上次执行结束
if (!flag) return;
flag = false;
fn();
setTimeout(() => {
flag = true;
}, delay);
};
}
/**
* 判空
* @param val
* @returns
*/
export function isEmpty(val: any) {
if(val === '' || val === {} || val === '{}' || val === [] || val === '[]' || val === null || val === undefined) {
return true
}else {
return false
}
}
/**
* 过滤对象中多余属性后赋值
* @param formKey 被赋值数据
* @param row 赋值数据
*/
export function filterKey(formKey: Object, row: Object ) {
Object.keys(formKey).forEach((key: string) => {
formKey[key] = row[key]
})
}
/**
* 获取assets静态资源 适用于处理多个链接的资源文件
* @param url 文件名
* @returns
*/
export const getAssetsFile = (url: string) => {
return new URL(`~@/assets/images/${url}`, import.meta.url).href
}
/**
* 判断是否文本溢出
* @param e 事件对象
* @returns
*/
export const isBeyond = (e: any) => {
const ev = window.event || e;
const textRange = (el: any) => {
const textContent = el;
const targetW = textContent.getBoundingClientRect().width;
const range = document.createRange();
range.setStart(textContent, 0);
range.setEnd(textContent, textContent.childNodes.length);
const rangeWidth = range.getBoundingClientRect().width;
return rangeWidth > targetW;
};
return !textRange(ev.target);
};
/**
* 防抖函数
* @param func
* @param delay
* @returns
*/
export const debounce = (func, delay) => {
let timer;
return function() {
clearTimeout(timer);
timer = setTimeout(func, delay);
};
}
/**
* 节流函数
* @param func
* @param delay
* @returns
*/
export const Throttle = (func, delay) => {
let timer;
let lastExecTime = 0;
return function(...args) {
const context = this;
const currentTime = Date.now();
if (currentTime - lastExecTime >= delay) {
lastExecTime = currentTime;
func.apply(context, args);
} else {
clearTimeout(timer);
timer = setTimeout(() => {
lastExecTime = currentTime;
func.apply(context, args);
}, delay - (currentTime - lastExecTime));
}
};
}
/**
* 将后端返回的数据,转换成echarts pie图需要的数据格式
* @param dataList
* @param nameField
* @param valueField
* @param paramsField
* @returns
*/
export const reconfigPie = (dataList, nameField, valueField, paramsField = undefined) => {
const result = dataList?.map((item) => ({
name: item[nameField],
value: item[valueField],
params: item[paramsField] && item[paramsField],
}));
return result;
}
/**
* 将后端返回的数据,转换成echarts bar图需要的数据格式
* @param dataList
* @param timeField
* @param yField
* @param nameField
* @param countField
* @returns
*/
export const reconfigBar = (dataList, timeField, yField, nameField, countField) => {
let format = {
dtX: [],
valY: [],
legend: [],
}
dataList.map((item) => {
format.dtX.push(
item[timeField]
);
for (let k of item[yField]) {
let isExist = format.valY.find(
(j) => j.name === k[nameField]
);
if (isExist) {
isExist.data.push(k[countField]);
} else {
format.valY.push({
name: k[nameField],
data: [k[countField]],
});
}
}
});
format.legend = format.valY?.map(item => {
return item.name
})
return format
}
/**
* params路由传参刷新就消失,将数据保存在sessionstorage中
* @param resultField
* @param sessionField
* @returns
*/
export const saveSessionParams = (resultField, sessionField,) => {
const route = router.currentRoute.value
let paramsVal = JSON.parse(sessionStorage.getItem(sessionField));
if(!isEmpty(paramsVal)) {
resultField = paramsVal
}else {
resultField = route.params
route.params && sessionStorage.setItem(
sessionField,
JSON.stringify(route.params)
);
}
return resultField
}
export const saveSessionParams1 = (resultField, sessionField) => {
const route = router.currentRoute.value;
const paramsVal = JSON.parse(sessionStorage.getItem(sessionField));
if (Object.keys(route.params).length > 0) { // 路由有传参
resultField = route.params
sessionStorage.setItem(sessionField, JSON.stringify(route.params));
} else { // 路由没有传参
if (paramsVal) {
resultField = paramsVal
}
}
return resultField
}