工具类小结 - Vue

一些常用的小方法单独写的一个类,方便日后复用,还在一点点积累完善中,也欢迎大家多多提供和改进优化,使其更加健壮;

export default {
    getValueByKey(data, key) {
        for (var i = 0; i < data.length; i++) {
            var item = data[i];
            if (item.key == key) {
                return item.value;
            }
        }
    },
    getKeyByValue(data, key) {
        for (var i = 0; i < data.length; i++) {
            var item = data[i];
            if (item.value == key) {
                return item.key;
            }
        }
    },
    getCookie(cookieVal) {
        /**
         * 获取cookie的值
         * cookieVal 参数是cookie中的key返回value
         * @type {string}
         */
        var currentCookie = "";
        document.cookie.split(";").forEach((item) => {
            if (this.trim(item.split("=")[0]) === cookieVal) {
                currentCookie = item.split("=")[1] || "";
            }
        });
        return currentCookie;
    },
    getUrlKey(name) {
        /*
        * 获取 URL 后面拼接的参数数据
        *
        * 调用方式
        * let token = YHUtility.getUrlKey('token');
        *
        * 通过路由的方式(拓展)
        * 地址:http://localhost:3333/#/index?id=001
        * console.log(this.$route.query.id)
        * 结果:001
        * */
        return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
    },
    getTimeStamp(time) {
        /*
        * 获取时间戳
        * @param time
        * @returns {number}
        * */
        return new Date(time.replace(/-/g, "/")).getTime();
    },
    imeDifferencet(starDateTime, endDateTime) {
        /*
        * 时间差
        * @param startDateTime
        * @param endDateTime
        * @returns {string}
        * @constructor
        * */
        let dataTime = endDateTime - starDateTime;
        let hours = dataTime / (3600 * 1000);
        return hours.toFixed(1);
    },
    formatDate(time, type, format) {
        /*
        * @param time
        * @param type (默认'yyyy-MM-dd HH:mm')
        * @param format
        * */
        var date = "";
        if (format) {
            date = time;
        } else {
            if (typeof time !== "number") {
                time = time.replace(/-/g, "/");
            }
            date = new Date(time);
        }

        type = type ? type : "yyyy-MM-dd HH:mm";

        var seperator1 = "-";
        var seperator2 = ":";
        var month = (date.getMonth() + 1).toString();
        var day = date.getDate().toString();
        var hours = date.getHours().toString();
        var minutes = date.getMinutes().toString();
        var seconds = date.getSeconds().toString();

        month = month.length === 1 ? ("0" + month) : month;
        day = day.length === 1 ? ("0" + day) : day;
        hours = hours.length === 1 ? ("0" + hours) : hours;
        minutes = minutes.length === 1 ? ("0" + minutes) : minutes;
        seconds = seconds.length === 1 ? ("0" + seconds) : seconds;

        if (type === "yyyy-MM-dd HH:mm:ss") {
            return date.getFullYear() + seperator1 + month + seperator1 + day + " " + hours + seperator2 + minutes + seperator2 + seconds;
        }
        else if (type === "yyyy-MM-dd HH:mm") {
            return date.getFullYear() + seperator1 + month + seperator1 + day + " " + hours + seperator2 + minutes;
        }
        else if (type === "yyyy-MM-dd") {
            return date.getFullYear() + seperator1 + month + seperator1 + day;
        }
        else if (type === "yyyy-MM") {
            return date.getFullYear() + seperator1 + month;
        }
        else if (type === "HH:mm") {
            return hours + seperator2 + minutes;
        }
    },
    trim(text) {
      /*去除首位空格*/
      return text == null ? "" : (text + "").replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
    },
    isEmpty() {
        /*
        * 字符串判空
        * @param value
        * @returns {boolean}
        * */
        return value.trim().replace(/(^s*)|(s*$)/g, "").length == 0;
    },
    checkSuffix(fileName) {
        /*
        * 校验图片真伪
        * @param fileName
        * @returns {boolean}
        * */
        const imgSuffixs = ["jpg", "jpeg", "png", "bmp", "gif"];
        const index = fileName.lastIndexOf(".");
        const suffix = fileName.substr(index + 1).toLowerCase();

        if (suffix) {
            return imgSuffixs.includes(suffix);
        }
        else  {
            return false;
        }
    },
    goBackView(that, cacheState) {
        /*返回上一页*/
        that.$route.meta.keepAlive = cacheState;// 用于上一页缓存(true & false)
        // that.$route.back(-1);
        that.$route.go(-1);
    },
    fastSort(arr, fn) {
        /*
        * 快速排序
        * @param arr
        * @param fn
        * @returns {*[]}
        * */
        let center = arr[0];
        let len = arr.length;
        let left = [];
        let right = [];
        let i = 1;

        for (; i < len; i++) {
            if (fn(center, arr[i])) {
                left.push(arr[i]);
            }
            else {
                right.push(arr[i]);
            }
        }

        if (1 < left.length) {
            left = this.fastSort(left, fn);
        }

        if (1 < right.length) {
            right = this.fastSort(right, fn);
        }

        return left.concat(center, right);
    },
    pickerType(type, value) {
        switch (type) {
            case "year":
                return `${value}年`;
            case "month":
                return `${value}月`;
            case "day":
                return `${value}日`;
            case "hour":
                return `${value}时`;
            case "minute":
                return `${value}分`;
        }
        return value;
    }
}

以上便是此次内容的小结,希望能对大家有所帮助!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值