mallBackend/src/utils/index.ts

88 lines
2.5 KiB
TypeScript
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.

/* eslint-disable @typescript-eslint/no-explicit-any */
// 深拷贝
export function deepMerge(...objs: any[]): any {
const result = Object.create(null)
objs.forEach((obj) => {
if (obj) {
Object.keys(obj).forEach((key) => {
const val = obj[key]
if (isPlainObject(val)) {
// 递归
if (isPlainObject(result[key])) {
result[key] = deepMerge(result[key], val)
} else {
result[key] = deepMerge(val)
}
} else {
result[key] = val
}
})
}
})
return result
}
export const isPlainObject = (val: any) =>
!!val && typeof val === 'object' && val.constructor === Object
//防抖
// fn 要执行的函数
// delay 执行函数
export const debounce = <T extends (...args: any[]) => ReturnType<T>>(
callback: T,
timeout: number
): ((...args: Parameters<T>) => void) => {
let timer: ReturnType<typeof setTimeout>
return (...args: Parameters<T>) => {
clearTimeout(timer)
timer = setTimeout(() => {
callback(...args)
}, timeout)
}
}
//封装节流
// fn 要执行的函数
// delay 执行函数
export const throttle = <T extends (...args: any[]) => ReturnType<T>>(
callback: T,
timeout: number
): ((...args: Parameters<T>) => void) => {
let valid = true
let timer: ReturnType<typeof setTimeout>
return (...args: Parameters<T>) => {
if (!valid) {
return false
}
valid = false
clearTimeout(timer)
timer = setTimeout(() => {
callback(...args)
valid = true
}, timeout)
}
}
export const exportBlob =(res:any)=>{
const blob = new Blob([res]); //res为后台返回的文件流注意参数是以数组的形式上传
const href = URL.createObjectURL(blob); //URL都要大写这点也要注意
const link = document.createElement("a") //生成a标签用于模拟下载
link.download = "test.xlsx"; //自定义下载文件名称
link.href = href //把生成的href赋值到a标签上在这里我遇到一个问题
//直接赋值无法把href赋值到a标签的href上不知道是不是因为封装框架的问题
//我采用了原生的方法
//link.setAttribute("href", href);
document.body.appendChild(link);
link.click();
//释放空间
document.body.removeChild("link");
URL.removeObjectURL(href);
}