js常用工具类

本文介绍了JavaScript中的日期处理函数如getYear、getMonth等,以及localStorage的set、get和remove方法。此外,还有axios的定制实例和数据处理辅助函数,如数组去重和参数转换。
摘要由CSDN通过智能技术生成
// 常用工具类
// npm i element-ui axios router
import axios from "axios";
import router from "@/router";
import { Message, Loading } from "element-ui";
/******************* 日期时间相关 ******************/
/**
 * 获取年
 * @param num 0:当前年
 * @returns 年
 */
function getYear(num: number = 0) {
    const t = new Date(new Date().getTime());
    const year: number = t.getFullYear() - num;
    const newTime = "" + year;
    return newTime;
}
/**
 * 获取月
 * @param num 0:当前月
 * @returns 月
 */
function getMonth(num: number = 0) {
    const t = new Date(new Date().getTime() - 30 * 24 * 60 * 60 * 1000 * num);
    const month = t.getMonth() + 1;
    const newTime = month < 10 ? "0" + month : month;
    return newTime;
}
/**
 * 获取日
 * @param num 0:当前日
 * @returns 日
 */
function getDate(num: number = 0) {
    const t = new Date(new Date().getTime() - 24 * 60 * 60 * 1000 * num);
    const day = t.getDate();
    const newTime = day < 10 ? "0" + day : day;
    return newTime;
}
/**
 *  获取年月
 * @param num 0:当前年月
 * @param splitSymbol 年月之间分隔符号
 * @returns 年月
 */
function getYM(num: number = 0, splitSymbol: string = "-") {
    const t = new Date(new Date().getTime() - 30 * 24 * 60 * 60 * 1000 * num);
    const year: number = t.getFullYear();
    const month = t.getMonth() + 1;
    const newTime = year + splitSymbol + (month < 10 ? "0" + month : month);
    return newTime;
}
/**
 *  获取年月日
 * @param num 0:当前年月日
 * @param splitSymbol 年月日之间分隔符号
 * @returns 年月日
 */
function getYMD(num: number = 0, splitSymbol: string = "-") {
    const t = new Date(new Date().getTime() - 24 * 60 * 60 * 1000 * num);
    const year: number = t.getFullYear();
    const month = t.getMonth() + 1;
    const day = t.getDate();
    const newTime =
        year +
        splitSymbol +
        (month < 10 ? "0" + month : month) +
        splitSymbol +
        (day < 10 ? "0" + day : day);
    return newTime;
}
/**
 *  获取年月日 00:00:00
 * @param num 0:当前年月日00:00:00
 * @param splitSymbol  年月日之间分隔符号
 * @param splitSymbol2  时分秒之间分隔符号
 * @returns 年月日 00:00:00
 */
function getYMD0(
    num: number = 0,
    splitSymbol: string = "-",
    splitSymbol2: string = ":"
) {
    const t = new Date(new Date().getTime() - 24 * 60 * 60 * 1000 * num);
    const year: number = t.getFullYear();
    const month = t.getMonth() + 1;
    const day = t.getDate();
    const newTime =
        year +
        splitSymbol +
        (month < 10 ? "0" + month : month) +
        splitSymbol +
        (day < 10 ? "0" + day : day) +
        ` 00${splitSymbol2}00${splitSymbol2}00`;
    return newTime;
}
/**
 *  获取年月日 时
 * @param num 0:当前年月日时
 * @param splitSymbol 年月日分隔符号
 * @returns 年月日时
 */
function getYMDH(num: number = 0, splitSymbol: string = "-") {
    const t = new Date(new Date().getTime() - 24 * 60 * 60 * 1000 * num);
    const year: number = t.getFullYear();
    const month = t.getMonth() + 1;
    const day = t.getDate();
    const hour = t.getHours();
    const newTime =
        year +
        splitSymbol +
        (month < 10 ? "0" + month : month) +
        splitSymbol +
        (day < 10 ? "0" + day : day) +
        " " +
        (hour < 10 ? "0" + hour : hour);
    return newTime;
}
/**
 *  获取年月日 时分
 * @param num 0:当前年月日时分
 * @param splitSymbol  年月日分隔符号
 * @param splitSymbol2 时分分隔符号
 * @returns 年月日时分
 */
function getYMDHm(
    num: number = 0,
    splitSymbol: string = "-",
    splitSymbol2: string = ":"
) {
    const t = new Date(new Date().getTime() - 24 * 60 * 60 * 1000 * num);
    const year: number = t.getFullYear();
    const month = t.getMonth() + 1;
    const day = t.getDate();
    const hour = t.getHours();
    const min = t.getMinutes();
    const newTime =
        year +
        splitSymbol +
        (month < 10 ? "0" + month : month) +
        splitSymbol +
        (day < 10 ? "0" + day : day) +
        " " +
        (hour < 10 ? "0" + hour : hour) +
        splitSymbol2 +
        (min < 10 ? "0" + min : min);
    return newTime;
}
/**
 *  获取年月 时分秒
 * @param num 0:当前年月日时分秒
 * @param splitSymbol 年月日分隔符号
 * @param splitSymbol2 时分秒分隔符号
 * @returns 年月日时分秒
 */
function getYMDHms(
    num: number = 0,
    splitSymbol: string = "-",
    splitSymbol2: string = ":"
) {
    const t = new Date(new Date().getTime() - 24 * 60 * 60 * 1000 * num);
    const year: number = t.getFullYear();
    const month = t.getMonth() + 1;
    const day = t.getDate();
    const hour = t.getHours();
    const min = t.getMinutes();
    const sec = t.getSeconds();
    const newTime =
        year +
        splitSymbol +
        (month < 10 ? "0" + month : month) +
        splitSymbol +
        (day < 10 ? "0" + day : day) +
        " " +
        (hour < 10 ? "0" + hour : hour) +
        splitSymbol2 +
        (min < 10 ? "0" + min : min) +
        splitSymbol2 +
        (sec < 10 ? "0" + sec : sec);
    return newTime;
}
/************************ localStorage ************************/
/**
 * 设置localStorage
 * @param key 键
 * @param value 值
 */
function setStorage(key: string, value: string) {
    try {
        window.localStorage.setItem(key, value);
    } catch (err) {
        console.log("setStorage=》=》=》", err);
    }
}
/**
 * 获取localStorage
 * @param key 键
 */
function getStorage(key: string) {
    try {
        const value = window.localStorage.getItem(key);
        return value;
    } catch (err) {
        console.log("getStorage=》=》=》", err);
    }
}
/**
 * 删除localStorage
 * @param key 键
 */
function removeStorage(key: string) {
    try {
        window.localStorage.removeItem(key);
    } catch (err) {
        console.log("removeStorage=》=》=》", err);
    }
}
/************************ axios 相关 ************************/
// 创建自定义axios实例
let instance: any;
function initAxios() {
    instance = axios.create({
        // baseURL: 'http://localhost:8081:8081/api',
        headers: {
            "Content-Type": "application/json;charset=UTF-8",
            // 'Content-Type': 'x-www-form-urlencoded',
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Credentials": true,
        },
        // 设置超时时间
        timeout: 30 * 1000,
        // 携带凭证
        // withCredentials: true,
        // 返回数据类型
        // responseType: "json",
    });
    // 登录页路由
    const loginPath = "/login";
    /**
     * request 请求拦截器=>请求发出前处理
     */
    instance.interceptors.request.use(
        (config: any) => {
            // if (config.url != '/api/sys/login') {
            // 发送请求时携带token
            const token = getStorage("token");
            if (token) {
                //  动态设置请求头
                config.headers.token = token;
            } else {
                if (window.location.hash !== "#" + loginPath) {
                    // 重定向到登录页面
                    router.push(loginPath);
                }
            }
            // }
            // post和put请求时,序列化入参
            if (config.method === "post" || config.method === "put") {
                config.data = config.data ? JSON.stringify(config.data) : "";
            }
            return config;
        },
        (error: any) => {
            // 接口返回失败
            console.log("接口请求失败=》=》=》", error.response);
            // 判断请求超时
            if (
                error.code === "ECONNABORTED" &&
                error.message.indexOf("timeout") !== -1
            ) {
                console.log("接口请求失败=》=》=》timeout请求超时");
            }
            Promise.reject(error.response);
        }
    );
    /**
     * request 响应拦截器=>处理响应数据
     */
    instance.interceptors.response.use(
        (response: any) => {
            const code = response.data.code;
            if (code === 401) {
                // 401 token失效 返回登录页面
                router.push(loginPath);
            }
            return Promise.resolve(response);
        },
        (error: any) => {
            // //请求失败,这个地方可以根据error.response.status统一处理一些界面逻辑,比如status为401未登录,可以进行重定向
            // router.replace({
            //     path: '/login',
            //     query: { redirect: router.currentRoute.fullPath }
            //    });
            return Promise.reject(error);
        }
    );
}
initAxios();
/**
 * get 异步请求
 * @param uri api
 * @param params 请求参数
 * @param successCallback 成功回调函数
 * @param isLoading 默认不显示loading
 */
function getRequest(
    uri: string,
    params: any,
    successCallback?: any,
    isLoading: boolean = false
) {
    // 显示loading
    let loading: any;
    if (isLoading) {
        loading = Loading.service({
            lock: true,
            text: "拼命加载中...",
            // spinner: 'el-icon-loading',
            background: "rgba(0, 0, 0, 0.2)",
        });
    }
    instance({
        url: uri,
        method: "get",
        params,
    })
        .then((ret: any) => {
            if (isLoading) {
                loading.close(); // 关闭loading
            }
            if (ret.data.code === 200 && ret.data.success === true) {
                successCallback(ret.data);
            } else {
                // Message.error(ret.data.msg);
                Message({
                    message: ret.data.msg,
                    type: "warning",
                });
            }
        })
        .catch((err: any) => {
            if (isLoading) {
                loading.close(); // 关闭loading
            }
            console.log("请求失败=》=》=》", err);
        });
}
/**
 * post 异步请求
 * @param uri api
 * @param params 请求参数
 * @param successCallback 成功回调函数
 * @param isLoading 默认不显示loading
 */
function postRequest(
    uri: string,
    params: any,
    successCallback?: any,
    isLoading: boolean = false
) {
    // 显示loading
    let loading: any;
    if (isLoading) {
        loading = Loading.service({
            lock: true,
            text: "拼命加载中...",
            // spinner: 'el-icon-loading',
            background: "rgba(0, 0, 0, 0.2)",
        });
    }
    // 请求对象
    let req;
    if (params.params) {
        // params类型
        req = instance({
            url: uri,
            method: "post",
            params: params.params,
        });
    } else if (params.data) {
        // data类型
        req = instance({
            url: uri,
            method: "post",
            data: params.data,
        });
    } else {
        // 默认params类型
        req = instance({
            url: uri,
            method: "post",
            data: params,
        });
    }
    req.then((ret: any) => {
        if (isLoading) {
            loading.close(); // 关闭loading
        }
        if (ret.data.code === 200 && ret.data.success === true) {
            successCallback(ret.data);
        } else {
            // errorCallback(ret.data);
            // Message.error(ret.data.msg);
            Message({
                message: ret.data.msg,
                type: "warning",
            });
        }
    }).catch((err: any) => {
        if (isLoading) {
            loading.close(); // 关闭loading
        }
        console.log("post请求失败=》=》=》", err);
    });
}
/**
 * get 异步请求 响应数据不是正规格式的
 * @param uri api
 * @param params 请求参数
 * @param successCallback 成功回调函数
 * @param isLoading 默认不显示loading
 */
function getRequestOther(
    uri: string,
    params: any,
    successCallback?: any,
    isLoading: boolean = false
) {
    // 显示loading
    let loading: any;
    if (isLoading) {
        loading = Loading.service({
            lock: true,
            text: "拼命加载中...",
            // spinner: 'el-icon-loading',
            background: "rgba(0, 0, 0, 0.2)",
        });
    }
    instance({
        url: uri,
        method: "get",
        params,
    })
        .then((ret: any) => {
            if (isLoading) {
                loading.close(); // 关闭loading
            }
            successCallback(ret);
        })
        .catch((err: any) => {
            if (isLoading) {
                loading.close(); // 关闭loading
            }
            console.log("get other 请求失败=》=》=》", err);
        });
}

/************************ 处理数据 ************************/
/**
 * 数组对象中根据键去重
 * @param arr 遍历的数组
 * @param key 需要去重的键
 * @returns 根据key去重后的值组成的数组
 * arr=[{name:1,value:2},{name:3,value:4},{name:5,value:6},{name:1,value:2},{name:7,value:8},{name:1,value:2},{name:9,value:10}]
 * key='value'
 * 输出 [2, 4, 6, 8, 10]
 */
function arrRemoveRepeat(arr: any, key: string) {
    const map = new Map();
    for (const item of arr) {
        if (!map.has(item[key])) {
            map.set(item[key], item);
        }
    }
    const newArr = [];
    for (const iterator of [...map.values()]) {
        newArr.push(iterator[key]);
    }
    return newArr;
}
/**
 * json对象转url参数
 * @param parame 对象
 * @returns url参数字符串
 */
function objToUrlParams(parame: any) {
    const params = Object.keys(parame)
        .map((key) => {
            return key + "=" + encodeURIComponent(parame[key]);
        })
        .join("&");
    return "?" + params;
}
/**
 * 导出 Excel
 * @param url api
 * @param params 参数对象 {a:1,b:2}
 */
function exportExcel(url: string, params: any) {
    // 方式一  动态创建a标签
    // const link = document.createElement("a");
    // link.style.display = "none";
    // link.href = that.exportObj.url;
    // link.click();
    // 方式二  iframe的方式
    const elemIF = document.createElement("iframe");
    elemIF.src = url + objToUrlParams(params);
    elemIF.style.display = "none";
    document.body.appendChild(elemIF);
}
/**
 * 合法uri
 * @param textval url
 * @returns boolean
 */
function validateURL(textval: string) {
    const urlregex = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/;
    return urlregex.test(textval);
}
/**
 * 合法邮箱
 * @param email 邮箱
 * @returns boolean
 */
function isEmail(email: string) {
    return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(
        email
    );
}
/**
 * 手机号码
 * @param s 手机号码
 * @returns boolean
 */
function isMobile(s: string) {
    return /^1[0-9]{10}$/.test(s);
}
/**
 * 电话号码
 * @param s 电话号码
 * @returns boolean
 */
function isPhone(s: string) {
    return /^([0-9]{3,4}-)?[0-9]{7,8}$/.test(s);
}
/************************ 导出 ************************/
export default {
    getYear,
    getMonth,
    getDate,
    getYM,
    getYMD,
    getYMD0,
    getYMDH,
    getYMDHm,
    getYMDHms,
    setStorage,
    getStorage,
    removeStorage,
    arrRemoveRepeat,
    objToUrlParams,
    getRequest,
    postRequest,
    getRequestOther,
    exportExcel,
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值