前端常用utils.js

import dayjs from 'dayjs';

export function cleanMultiSlash(url) {
    return url.replace(/([^:]\/)\/+/g, '$1');
}

export const toLogin = (signinUrl, appId) => {
    // const url = encodeURIComponent(`${window.location.origin + window.location.pathname}#/`);
    const url = encodeURIComponent(window.location.href);
    const redirectUrl = `${signinUrl}?appid=${appId}&url=${url}`;
    console.log(signinUrl, redirectUrl);
    window.location.href = redirectUrl;
};

export function downFileLink(data) {
    try {
        const blob = data.data;
        const _fileName = data.headers['content-disposition'].split(';')[1].split('=')[1]; // 文件名,中文无法解析的时候会显示 _(下划线),生产环境获取不到
        if (navigator.msSaveBlob) {
            return navigator.msSaveBlob(blob, _fileName);
        }
        const link = document.createElement('a');
        link.style.display = 'none';
        // 兼容不同浏览器的URL对象
        const url = window.URL || window.webkitURL || window.moxURL;
        link.href = url.createObjectURL(blob);
        link.download = decodeURI(_fileName);
        link.click();
        window.URL.revokeObjectURL(url);
    } catch (e) {
        console.log('下载的文件出错', e);
    }
}

export const formatDateTime = (time, format = 'YYYY-MM-DD HH:mm:ss') => {
    if (time) {
        return dayjs(time).format(format);
    }
    return '';
};


export const transferDate = (value) => {
    console.log('value: ', value);
    const result = new Date(value).getTime();
    console.log('result: ', result);
    return result;
};

// 获取url参数
export function getUrlParams() {
    let search = window.location.href;
    const index = search.indexOf('?');
    if (index === -1) {
        return {};
    }
    search = search.substring(index + 1);
    const searchArr = search.split('&');
    const param = {};
    searchArr.forEach((item) => {
        const paramKey = item.substring(0, item.indexOf('='));
        const paramVal = item.substring(item.indexOf('=') + 1);
        param[paramKey] = paramVal;
    });
    return param;
}

你可能感兴趣的:(javascript,前端,开发语言)