一、json转字符串
export const jsonToUrlParams = (params) => {
const query = [];
Object.keys(params)
.forEach((key) => {
if (params[`${key}`]) {
query.push(`${key}=${params[`${key}`]}`);
}
});
if (query.length) return `?${query.join('&')}`;
return '';
};
二、用a标签打开新页面
export const open = ({ url, params = {} }) => {
const a = document.createElement('a');
a.target = '_blank';
a.href = `${url}${jsonToUrlParams(params)}`;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
三、用a标签下载文件
export const syncExportFile = ({
url, params = {}, fileName = '', target = '_blank',
}) => {
const a = document.createElement('a');
if ('download' in a) {
if (fileName) a.download = decodeURIComponent(fileName);
}
a.target = target;
a.href = typeof url === 'string' ? `${url}${jsonToUrlParams(params)}` : url;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
四、文件链接转文件流下载
export const asyncExportFile = (
{
method = 'GET',
url,
params = {},
options = {},
},
) => axios({
method,
url,
[method === 'GET' ? 'params' : 'data']: {
...params,
},
responseType: 'blob',
...options,
})
.then((res) => {
if (res) {
const { data, headers } = res;
const blob = new Blob([data], { type: 'application/octet-stream' });
const fileName = headers['content-disposition'].replace(/\w+;[\s]?filename=(.*)/, '$1');
if (typeof window.navigator.msSaveBlob === 'undefined') {
const URL = window.URL.createObjectURL(blob);
syncExportFile({
url: URL,
fileName,
});
window.URL.revokeObjectURL(url);
} else {
window.navigator.msSaveBlob(blob, fileName);
}
}
return res;
});
五、数据扁平化
export const flatten = (arr) => arr.reduce((prev, next) => prev.concat(Array.isArray(next)
? flatten(next)
: next), []);