常用utils总结

2022-03-28  本文已影响0人  萤火kin

号码中间加星

plusXing(scope.row.cardNo, 4, 4)
// 加星
// 三个参数分别为传入的字符串value值、前几位保留位数、后几位保留位数
    plusXing(str, frontLen, endLen) {
      let len = str.length - frontLen - endLen;
      let xing = "";
      for (var i = 0; i < len; i++) {
        xing += "*";
      }
      return str.substr(0, frontLen) + xing + str.substr(str.length - endLen);
    },

字典回显【单项及多项】


// 第一个参数为字典项,第二个参数为选项value
// dictValue为字典项的value字段,dictLabel为字典项的label字段

// 回显数据字典
'value' => 'label'
export function selectDictLabel(datas, value) {
    var actions = [];
    Object.keys(datas).some((key) => {
        if (datas[key].dictValue == ('' + value)) {
            actions.push(datas[key].dictLabel);
            return true;
        }
    })
    return actions.join('');
}

// 回显数据字典(字符串数组)
'value1,value2' => 'label1,label2'
export function selectDictLabels(datas, value, separator) {
    var actions = [];
    var currentSeparator = undefined === separator ? "," : separator;
    var temp = value.split(currentSeparator);
    Object.keys(value.split(currentSeparator)).some((val) => {
        Object.keys(datas).some((key) => {
            if (datas[key].dictValue == ('' + temp[val])) {
                actions.push(datas[key].dictLabel + currentSeparator);
            }
        })
    })
    return actions.join('').substring(0, actions.join('').length - 1);
}

cookie获取、设置、清除

需js-cookie依赖

import Cookies from 'js-cookie'

const TokenKey = 'Admin-Token'

export function getToken() {
  return Cookies.get(TokenKey)
}

export function setToken(token) {
  return Cookies.set(TokenKey, token)
}
export function removeToken() {
  return Cookies.remove(TokenKey)
}

字数超过加...

// val为需要加...的value值,num为第几项之后加...
export function ellipsisVal(val,num) {
  if(val.length > num){
    return val.substr(0, num) + '...'
  } else {
    return va
  }
}

ellipsisVal(params.row.content)
// 超过三十个字符加...
export const ellipsisVal = (val) => {
    return val.length > 30 ?
        val.substr(0, 30) + '...' :
        val
}

过滤器 货币金额格式化

// 需要accounting-js依赖

$Accounting(settlementForm.deposit)
// 过滤器
import accounting from "accounting-js"


Vue.prototype.$Accounting = (amount, AccountingObj = AccountingObj) => {
    return `₹ ${accounting.formatNumber(amount, AccountingObj)}`
};



// accoount from obj 金额格式化统一格式
export const AccountingObj = {
    symbol: '₹',
    decimal: '.',
    thousand: ',',
    precision: 2
}

// 保留四位小数点
export const AccountingObjFour = {
    symbol: '₹',
    decimal: '.',
    thousand: ',',
    precision: 4
}

时间相关

this.changePicker([calculateTimes(0, 0, -6) + ' 00:00:00', getTodayTimes() + ' 23:59:59']);
changePicker (val) {
            this.dateTime = val;
            if (val) {
                this.searchObj.startTime = val[0];
                this.searchObj.endTime = resetEndTime(val[1]);
                this.dateTime[1] = resetEndTime(val[1]);
            } else {
                this.searchObj.startTime = "";
                this.searchObj.endTime = "";
            }
        },
// 获取当前 年月日 格式化
export const getTodayTimes = () => {
    let myDate = new Date(); //获取当前年份(2位)
    let year = myDate.getFullYear(); //获取完整的年份(4位,1970-????)
    let month = ("0" + (myDate.getMonth() + 1)).slice(-2); //获取当前月份(0-11,0代表1月)
    let day = myDate.getDate(); //获取当前日(1-31)
    return year + '-' + month + "-" + day;
}

// 时间往前推算
export const calculateTimes = (year, month, day) => {
    const date = new Date();
    let nowYear = date.getFullYear() + year;
    let nowMonth = date.getMonth() + month;
    let nowDay = date.getDate() + day;
    const nowDate = new Date(nowYear, nowMonth, nowDay, 0, 0, 0);
    return `${nowDate.getFullYear()}-${nowDate.getMonth() + 1}-${nowDate.getDate()}`
}

/**
 *
 * @resetEndTime 重置结束时间
 * @param endTime 结束时间
 */
export const resetEndTime = (endTime) => {
    if (!endTime) return endTime;
    const dirStrIndex = endTime.indexOf(' ');
    const selectTime = endTime.substring(dirStrIndex + 1);
    if (selectTime === '00:00:00') {
        // 用户未选择时间,将时间替换为一天的结束时间
        endTime = endTime.replace('00:00:00', '23:59:59');
    }
    return endTime;
};

判断是否为移动端

hasMobile()
//  判断是否为移动端
export function hasMobile () {
    let isMobile = false;
    if((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
        // console.log('移动端');
        isMobile = true;
    }
    if (document.body.clientWidth < 800) {
        isMobile = true;
    }
    return isMobile
}

根据权重sort排序

changeListSort(this.menuData);
// 根据权重sort排序
export const changeListSort = (list) => {
    list.sort(function(a, b) {
        return b.sort - a.sort;
    });
    list.forEach(item => {
        if (item.children && item.children.length > 0) {
            changeListSort(item.children)
        }
    });
}

下载文件方法

downloadDoc(res.data, "账户余额变动表");
// 下载文件方法
export function downloadDoc(content, filename) {
    var blob = new Blob([content], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
    });
    if ("download" in document.createElement("a")) { // 非IE下载
        const elink = document.createElement("a")
        elink.download = filename + ".xlsx";
        elink.style.display = "none"
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
    } else { // IE10+下载
        navigator.msSaveBlob(blob, filename)
    }
};

复制功能

// 复制功能
export const CopyText = (content) => {
    var oInput = document.createElement('input'); //创建一个隐藏input(重要!)
    oInput.value = content; //赋值
    document.body.appendChild(oInput);
    oInput.select(); // 选择对象
    document.execCommand("Copy"); // 执行浏览器复制命令
    oInput.className = 'oInput';
    oInput.style.display = 'none';
    document.body.removeChild(oInput);
}
上一篇 下一篇

猜你喜欢

热点阅读