封装js工具类方法

//api公共工具类
 export function getUrl(url, params) {
    if (params) {
      Object.keys(params).map((key, index) => {
        const pre = index == 0 ? "?" : "&";
        let val = params[key];
        if (val == null) val = "";
        url += `${pre}${key}=${val}`;
      });
    }
    return url;
  }

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime (time, cFormat) {
    if (arguments.length === 0 || !time) {
        return null
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if ((typeof time === 'string')) {
            if ((/^[0-9]+$/.test(time))) {
                // support "1548221490638"
                time = parseInt(time)
            } else {
                // support safari
                // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
                time = time.replace(new RegExp(/-/gm), '/')
            }
        }

        if ((typeof time === 'number') && (time.toString().length === 10)) {
            time = time * 1000
        }
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
        return value.toString().padStart(2, '0')
    })
    return time_str
}

//设置cookie
export function setCookie(name, value, day) {
    let date = new Date();
    date.setDate(date.getDate() + day);
    document.cookie = name + '=' + value + ';expires=' + date;
}
// 获取cookie
export function getCookie(name) {
    let reg = RegExp(name + '=([^;]+)');
    let arr = document.cookie.match(reg);
    if (arr) {
        return arr[1];
    } else {
        return '';
    }
}

// 深拷贝
export function deepClone (obj) {
    let objClone = Array.isArray(obj) ? [] : {};
    if (obj && typeof obj === "object") {
        for (let key in obj) {
            //判断ojb子元素是否为对象,如果是,递归复制
            if (obj[key] && typeof obj[key] === "object") {
                objClone[key] = deepClone(obj[key]);
            } else {
                //如果不是,简单复制
                objClone[key] = obj[key];
            }
        }
    }
    return objClone;
}
export function getNowTime() {
      let date = new Date()
      let year = date.getFullYear()
      let month = date.getMonth() < 9 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      let dates = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      let hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      let minute = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      let second = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      let milliSeconds = date.getMilliseconds()
      let currentTime = `${year}${month}${dates}${hour}${minute}${second}${milliSeconds}`
      this.formData.name = currentTime
    },
/**防抖: n秒后执行,n秒内触发重新定时
 *
 * @param {*} fn
 * @param {*} wait
 * @param {*} opts {key: 手动赋予key值,或自定义key值前缀, customKey: 自定义key值计算方法,参数为函数参数数组[...arguments]}
 * @returns func 防抖函数,只需代入参数执行
 */
 export function debounce(fn, wait, opts = {}) {
    let timer = {};
    let key = opts.key || Math.random().toString(36).slice(2);
    return function () {
      let isCustom = Boolean(opts.customKey);
      let index = isCustom
        ? opts.key + "." + opts.customKey([...arguments])
        : key;
      clearTimeout(timer[index]);
      timer[index] = setTimeout(() => {
        fn.call(this, ...arguments);
      }, wait);
    };
  }

// 请求出错提示框(包含重新登录操作)
export function errorTip(errMsg) {
    openPromptBox('error', errMsg +'!').then(() => {
        if (errMsg == '用户登录信息过期,请重新登录'){
            store.dispatch('user/logout');
            store.dispatch('setting/removeUrls');
            router.push('/');
        }
    }).catch(() => {});
}

// 总毫秒转时分秒
export function changeTime(val){
    let day= Math.floor(val/1000/60/60/24)
    let hour= Math.floor(val/1000/60/60-(day*24))
    let min= Math.floor(val/1000/60- (24 * 60 * day) - (60 * hour))
    let second= Math.floor(val/1000-(24 * 60 * 60 * day) - (60 * 60 * hour) - (60 * min))
    return `${day}天${hour}时${min}分${second}秒`
  }

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值