• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

vue项目封装的有用的公共方法集合

武飞扬头像
五月是five month
帮助1

1、数据类型判断以及判断是否为数字类型或者数字型字符串

  1.  
    //万能型方法
  2.  
    function typeOf(obj) {
  3.  
    const toString = Object.prototype.toString
  4.  
    const map = {
  5.  
    '[object Boolean]': 'boolean',
  6.  
    '[object Number]': 'number',
  7.  
    '[object String]': 'string',
  8.  
    '[object Function]': 'function',
  9.  
    '[object Array]': 'array',
  10.  
    '[object Date]': 'date',
  11.  
    '[object RegExp]': 'regExp',
  12.  
    '[object Undefined]': 'undefined',
  13.  
    '[object Null]': 'null',
  14.  
    '[object Object]': 'object'
  15.  
    }
  16.  
    return map[toString.call(obj)]
  17.  
    }
  18.  
    //简单性
  19.  
    function isNumber(obj) {
  20.  
    return obj === obj
  21.  
    }
  22.  
     
  23.  
    function isNull(arg1) {
  24.  
    return !!(!arg1 && arg1 !== 0 && typeof arg1 !== 'boolean')
  25.  
    }
  26.  
     
  27.  
    function isString(obj) {
  28.  
    return obj === obj ''
  29.  
    }
  30.  
    function isBoolean(obj) {
  31.  
    return obj === !!obj
  32.  
    }
  33.  
     
  34.  
    function isObject(obj) {
  35.  
    return typeof obj === 'object'
  36.  
    }
  37.  
     
  38.  
    /**
  39.  
    * 判断检测的字符是否为数字或者是数字类型的字符串,比如123,123.45,'123','123.45', -123,-123.45,'-123','-123.45'均返回true
  40.  
    * @param val 检测的字符
  41.  
    * @returns {Boolean} 如果是返回true,不是返回false
  42.  
    */
  43.  
    function ifTurnToNumber(val) {
  44.  
    var regPos = /^\d (\.\d )?$/ // 非负浮点数
  45.  
    var regNeg = /^(-(([0-9] \.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9] )|([0-9]*[1-9][0-9]*)))$/ // 负浮点数
  46.  
    if (regPos.test(val) || regNeg.test(val)) {
  47.  
    return true
  48.  
    } else {
  49.  
    return false
  50.  
    }
  51.  
    }
学新通

2、如果是IE浏览器return 返回的就是true

  1.  
    function checkIE() {
  2.  
    return (
  3.  
    '-ms-scroll-limit' in document.documentElement.style &&
  4.  
    '-ms-ime-align' in document.documentElement.style
  5.  
    )
  6.  
    }
  7.  
     
  8.  
    //如果是IE浏览器,返回的就是true

3、深拷贝

  1.  
    /**
  2.  
    * @desc 深拷贝,结构化拷贝,支持string,number,date,reg等格式,不支持function拷贝
  3.  
    * @param {Any} obj
  4.  
    * @param {WeakMap} hash
  5.  
    * @return {Any}
  6.  
    */
  7.  
     
  8.  
    function deepClone(obj, hash = new WeakMap()) {
  9.  
    if (obj == null || typeof obj !== 'object') return obj
  10.  
    let cloneObj
  11.  
    const Constructor = obj.constructor
  12.  
    switch (Constructor) {
  13.  
    case RegExp:
  14.  
    cloneObj = new Constructor(obj)
  15.  
    break
  16.  
    case Date:
  17.  
    cloneObj = new Constructor(obj.getTime())
  18.  
    break
  19.  
    default:
  20.  
    if (obj._isAMomentObject) {
  21.  
    cloneObj = new Constructor(obj)
  22.  
    }
  23.  
    if (hash.has(obj)) return hash.get(obj)
  24.  
    cloneObj = new Constructor()
  25.  
    hash.set(obj, cloneObj)
  26.  
    // //console.log(2, hash.get(obj))
  27.  
    }
  28.  
    for (const key in obj) {
  29.  
    // //console.log(3, key, cloneObj)
  30.  
    cloneObj[key] = isObject(obj[key]) ? deepClone(obj[key], hash) : obj[key]
  31.  
    // //console.log(4, key, cloneObj[key])
  32.  
    }
  33.  
    return cloneObj
  34.  
    }
学新通

4、数组去重

  1.  
    /*
  2.  
    * JSON数组去重
  3.  
    * @param: [array] json Array
  4.  
    * @param: [string] 唯一的key名,根据此键名进行去重
  5.  
    */
  6.  
    function uniqueArray(array, key) {
  7.  
    var result = [array[0]]
  8.  
    for (var i = 1; i < array.length; i ) {
  9.  
    var item = array[i]
  10.  
    var repeat = false
  11.  
    for (var j = 0; j < result.length; j ) {
  12.  
    if (item[key] == result[j][key]) {
  13.  
    repeat = true
  14.  
    break
  15.  
    }
  16.  
    }
  17.  
    if (!repeat) {
  18.  
    result.push(item)
  19.  
    }
  20.  
    }
  21.  
    return result
  22.  
    }
  23.  
     
  24.  
    /**
  25.  
    * 两个数组去重
  26.  
    * @param {Array} originList 原始数组
  27.  
    * @param {Array} currentList 当前数组
  28.  
    * @param {String} sortKey 去重字段
  29.  
    * @return {Array} 返回新数组中不重复的部分
  30.  
    */
  31.  
    function Duplicate(originList, currentList, sortKey = 'id') {
  32.  
    const map = {}
  33.  
    originList.forEach(e => {
  34.  
    map[e[sortKey]] = true
  35.  
    })
  36.  
    return currentList.filter(e => !map[e[sortKey]])
  37.  
    }
  38.  
     
  39.  
    // 数组包数组去重
  40.  
    function unique(arr) {
  41.  
    arr = arr.filter(item => item.every(item => item)) // 去除[0,0]
  42.  
    for (let i = 0, len = arr.length; i < len; i ) {
  43.  
    for (let j = i 1, len = arr.length; j < len; j ) {
  44.  
    if (JSON.stringify(arr[i]) === JSON.stringify(arr[j])) {
  45.  
    arr.splice(j, 1)
  46.  
    j-- // 每删除一个数j的值就减1
  47.  
    len-- // j值减小时len也要相应减1(减少循环次数,节省性能)
  48.  
    // console.log(j,len)
  49.  
    }
  50.  
    }
  51.  
    }
  52.  
    return arr
  53.  
    }
  54.  
     
  55.  
    /**
  56.  
    * 数组元素为对象的去重方法 ES5方法
  57.  
    * @param arr 原数组
  58.  
    * @param type 根据元素的某个属性进行去重
  59.  
    * @returns {Array} 返回去重后的新的数组
  60.  
    */
  61.  
    function Es5duplicate(arr, type) {
  62.  
    var newArr = []
  63.  
    var tArr = []
  64.  
    if (arr.length == 0) {
  65.  
    return arr
  66.  
    } else {
  67.  
    if (type) {
  68.  
    for (var i = 0; i < arr.length; i ) {
  69.  
    if (!tArr[arr[i][type]]) {
  70.  
    newArr.push(arr[i])
  71.  
    tArr[arr[i][type]] = true
  72.  
    }
  73.  
    }
  74.  
    return newArr
  75.  
    } else {
  76.  
    for (var j = 0; j < arr.length; j ) {
  77.  
    if (!tArr[arr[j]]) {
  78.  
    newArr.push(arr[j])
  79.  
    tArr[arr[j]] = true
  80.  
    }
  81.  
    }
  82.  
    return newArr
  83.  
    }
  84.  
    }
  85.  
    }
  86.  
     
  87.  
    /**
  88.  
    * 数组元素为对象的去重方法 ES6方法
  89.  
    * @param arr 原数组
  90.  
    * @param type 根据元素的某个属性进行去重
  91.  
    * @returns {Array} 返回去重后的新的数组
  92.  
    */
  93.  
    function Es6duplicate(arr, type) {
  94.  
    var hash = {}
  95.  
    return arr.reduce(function(item, next) {
  96.  
    hash[next[type]] ? '' : hash[next[type]] = true && item.push(next)
  97.  
    return item
  98.  
    }, [])
  99.  
    }
学新通

5、对象合并,仅支持一层

  1.  
    /**
  2.  
    * 合并两个map ,仅支持一层
  3.  
    * @param {*} map1
  4.  
    * @param {*} map2
  5.  
    */
  6.  
    function mergeMap(map1, map2) {
  7.  
    for (const key in map2) {
  8.  
    if (map1.hasOwnProperty(key)) {
  9.  
    Object.assign(map1[key], map2[key])
  10.  
    } else {
  11.  
    map1[key] = map2[key]
  12.  
    }
  13.  
    }
  14.  
    return map1
  15.  
    }
学新通

6、保留任意位小数

  1.  
    /**
  2.  
    * 保留任意位小数
  3.  
    * @param {*} num 实际数字
  4.  
    * @param {*} decimal 保留位数
  5.  
    */
  6.  
    function keepAnyDecimal(num, decimal = 2) {
  7.  
    const level = Math.pow(10, decimal)
  8.  
    var result = parseFloat(num)
  9.  
    if (isNaN(result)) {
  10.  
    return ''
  11.  
    }
  12.  
    result = Math.round(num * level) / level
  13.  
    return result
  14.  
    }

7、树形对象数组遍历查询

  1.  
    /**
  2.  
    * 树形对象数组遍历查询
  3.  
    * @param {String} code 遍历字段key
  4.  
    * @param {String} val 遍历字段value
  5.  
    * @param {Array} arr 遍历数组
  6.  
    * @return {Object} 遍历得到的对象
  7.  
    */
  8.  
    function findCode(arr, code, val) {
  9.  
    const list = getList(arr)
  10.  
    return list.find(e => e[code] === val)
  11.  
    }
  12.  
     
  13.  
    function getList(list, total = []) {
  14.  
    list.forEach(e => {
  15.  
    total.push(e)
  16.  
    if (e.children) {
  17.  
    getList(e.children, total)
  18.  
    }
  19.  
    })
  20.  
    return total
  21.  
    }
  22.  
     
  23.  
    function getChildNode(node, nodes, code, children = 'coverages') {
  24.  
    if (node != null) {
  25.  
    nodes.push(node)
  26.  
    const childrens = node[children]
  27.  
    ? node[children]
  28.  
    : node.children
  29.  
    ? node.children
  30.  
    : []
  31.  
    for (let i = 0; i < childrens.length; i ) {
  32.  
    getChildNode(childrens[i], nodes)
  33.  
    }
  34.  
    }
  35.  
    return nodes.find(e => e.key == code)
  36.  
    }
学新通

8、判断字节长度

  1.  
    /**
  2.  
    *判断字节长度
  3.  
    * @param {String} val
  4.  
    * @return {Number} 字符串长度
  5.  
    */
  6.  
    function getByteLen(val) {
  7.  
    // 传入一个字符串
  8.  
    if (!val) return false
  9.  
    let len = 0
  10.  
    for (var i = 0; i < val.length; i ) {
  11.  
    if (val[i].match(/[^\x00-\xff]/gi) != null) {
  12.  
    // 全角
  13.  
    len = 2
  14.  
    } else {
  15.  
    len = 1
  16.  
    } // 如果是全角,占用两个字节
  17.  
    }
  18.  
    return len
  19.  
    }
学新通

9、正则校验相关

  1.  
    /**
  2.  
    * 名称校验规则
  3.  
    * @param {String} str 获取输入的名称
  4.  
    * @return {Boolean} 返回是否校验通过 true为通过, false为不通过
  5.  
    */
  6.  
    function nameRexp(str, required = true) {
  7.  
    if (!required) {
  8.  
    return {
  9.  
    status: true
  10.  
    }
  11.  
    }
  12.  
    if (!str) {
  13.  
    return {
  14.  
    message: '用户名不能为空',
  15.  
    status: false
  16.  
    }
  17.  
    }
  18.  
    str = str.trim()
  19.  
    // 校验特殊字符
  20.  
    // let special = /[^~!@#$%\^&* |}{"::<>?\/;''\[\]\\=`]$/;
  21.  
    // let special = partyPersonNameNewReg;
  22.  
    // if (!special.test(str)) {
  23.  
    // return {
  24.  
    // message: "录入结果应不包含特殊字符,请重新录入。",
  25.  
    // status: false
  26.  
    // };
  27.  
    // }
  28.  
    str = str.replace(/[\r\n]/g, '')
  29.  
    if (getByteLen(str) < 3) {
  30.  
    return {
  31.  
    message: '请输入3个字节以上的长度',
  32.  
    status: false
  33.  
    }
  34.  
    }
  35.  
    // 判断是否含有数字,有数字 校验拦截
  36.  
    const Num = /[0-9]/
  37.  
    if (Num.test(str)) {
  38.  
    return {
  39.  
    message: '名称不允许含有数字',
  40.  
    status: false
  41.  
    }
  42.  
    }
  43.  
    // 校验是否为全中文
  44.  
    const ZH = new RegExp('[\\u4E00-\\u9FFF] $', 'g')
  45.  
    if (ZH.test(str)) {
  46.  
    // 当输入值为全中文时,校验是否有空格
  47.  
    if (str.indexOf(' ') != -1) {
  48.  
    return {
  49.  
    message: '名称为全中文时中间不允许含有空格',
  50.  
    status: false
  51.  
    }
  52.  
    } // 有空格
  53.  
    }
  54.  
    return {
  55.  
    status: true
  56.  
    }
  57.  
    }
  58.  
     
  59.  
    /**
  60.  
    * 身份证检验规则
  61.  
    * @param {String} IDCard 获取输入的身份证号码
  62.  
    * @return {Boolean} 返回是否校验通过 true为通过, false为不通过
  63.  
    */
  64.  
    function idCard(IDCard) {
  65.  
    // 身份证地区
  66.  
    const areaID = {
  67.  
    11: '北京',
  68.  
    12: '天津',
  69.  
    13: '河北',
  70.  
    14: '山西',
  71.  
    15: '内蒙古',
  72.  
    21: '辽宁',
  73.  
    22: '吉林',
  74.  
    23: '黑龙江',
  75.  
    31: '上海',
  76.  
    32: '江苏',
  77.  
    33: '浙江',
  78.  
    34: '安徽',
  79.  
    35: '福建',
  80.  
    36: '江西',
  81.  
    37: '山东',
  82.  
    41: '河南',
  83.  
    42: '湖北',
  84.  
    43: '湖南',
  85.  
    44: '广东',
  86.  
    45: '广西',
  87.  
    46: '海南',
  88.  
    50: '重庆',
  89.  
    51: '四川',
  90.  
    52: '贵州',
  91.  
    53: '云南',
  92.  
    54: '西藏',
  93.  
    61: '陕西',
  94.  
    62: '甘肃',
  95.  
    63: '青海',
  96.  
    64: '宁夏',
  97.  
    65: '新疆',
  98.  
    71: '台湾',
  99.  
    81: '香港',
  100.  
    82: '澳门',
  101.  
    91: '国外'
  102.  
    }
  103.  
    // 41072119780706355X
  104.  
    // var iSum = 0
  105.  
    if (!/^\d{17}(\d|x)$/i.test(IDCard)) {
  106.  
    return {
  107.  
    status: false,
  108.  
    message: '你输入的身份证长度或格式错误!'
  109.  
    }
  110.  
    }
  111.  
    IDCard = IDCard.replace(/x$/i, 'a')
  112.  
    if (areaID[parseInt(IDCard.substr(0, 2))] == null) {
  113.  
    return {
  114.  
    status: false,
  115.  
    message: '你的身份证地区非法!'
  116.  
    }
  117.  
    }
  118.  
    var sBirthday =
  119.  
    IDCard.substr(6, 4)
  120.  
    '-'
  121.  
    Number(IDCard.substr(10, 2))
  122.  
    '-'
  123.  
    Number(IDCard.substr(12, 2))
  124.  
    var d = new Date(sBirthday.replace(/-/g, '/'))
  125.  
    if (
  126.  
    sBirthday !=
  127.  
    d.getFullYear() '-' (d.getMonth() 1) '-' d.getDate()
  128.  
    ) {
  129.  
    return {
  130.  
    status: false,
  131.  
    message: '身份证上的出生日期非法!'
  132.  
    }
  133.  
    }
  134.  
    // for (var i = 17; i >= 0; i--)
  135.  
    // iSum = (Math.pow(2, i) % 11) * parseInt(IDCard.charAt(17 - i), 11)
  136.  
    // if (iSum % 11 != 1)
  137.  
    // return {
  138.  
    // status: false,
  139.  
    // message: '你输入的身份证号非法!'
  140.  
    // }
  141.  
    // aCity[parseInt(sId.substr(0,2))] "," sBirthday "," (sId.substr(16,1)%2?"男":"女");//此次还可以判断出输入的身份证号的人性别
  142.  
    return {
  143.  
    status: true,
  144.  
    message: '校验成功!'
  145.  
    }
  146.  
    }
  147.  
     
  148.  
    /**
  149.  
    * 根据身份证获取性别
  150.  
    * @param {String} idCard 获取输入的身份证号码
  151.  
    * @return {String} 返回性别 {男, 女}
  152.  
    */
  153.  
    function IDCardSex(idCard) {
  154.  
    var sexMap = {
  155.  
    0: '女',
  156.  
    1: '男'
  157.  
    }
  158.  
    if (idCard && idCard.length === 15) {
  159.  
    return sexMap[idCard.substring(14, 15) % 2]
  160.  
    } else if (idCard && idCard.length === 18) {
  161.  
    return sexMap[idCard.substring(16, 17) % 2]
  162.  
    } else {
  163.  
    // 不是15或者18,null
  164.  
    return 'error'
  165.  
    }
  166.  
    }
  167.  
     
  168.  
    /**
  169.  
    * 校验比例输入 (输入为数字且在0-100之内)
  170.  
    * @param {String Number} num 输入的比例值
  171.  
    * @return {Boolean} 校验是否通过 true:通过 / false:未通过
  172.  
    */
  173.  
    function propNum(num) {
  174.  
    const regExp = /^(?:[1-9]?\d|100)$/
  175.  
    if (regExp.test(num)) {
  176.  
    return true
  177.  
    } else {
  178.  
    return false
  179.  
    }
  180.  
    }
  181.  
     
  182.  
    /**
  183.  
    * 校验输入的年龄 (输入为数字且在0-120之内)
  184.  
    * @param {String Number} num 输入的年龄
  185.  
    * @return {Boolean} 校验是否通过 true:通过 / false:未通过
  186.  
    */
  187.  
    function ageRexp(num) {
  188.  
    const rexp = /^(?:[1-9][0-9]?|1[01][0-9]|120)$/
  189.  
    if (rexp.test(num)) {
  190.  
    return true
  191.  
    } else {
  192.  
    return false
  193.  
    }
  194.  
    }
  195.  
     
  196.  
    /**
  197.  
    * 联系电话校验
  198.  
    * @param {String Number} num 录入的号码(手机号或者固定电话)
  199.  
    * @return {Boolean} 校验是否通过 true:通过 / false:未通过
  200.  
    */
  201.  
    function TelphoneNumber(num) {
  202.  
    const str = num.toString()
  203.  
    // 手机号校验正则
  204.  
    const tel = /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/
  205.  
    // 固定电话校验正则 (不含区号)
  206.  
    const rexp = /\d{3}-\d{8}|\d{4}-\d{7}/
  207.  
    if (!str.length) return false
  208.  
    // //console.log(str.includes('-'))
  209.  
    if (str.includes('-')) {
  210.  
    const bool = rexp.test(str)
  211.  
    return bool
  212.  
    } else {
  213.  
    const bool = tel.test(str)
  214.  
    return bool
  215.  
    }
  216.  
    }
  217.  
     
  218.  
    // 检查特殊字符
  219.  
    function specialCharactersCheck(str) {
  220.  
    const pattern = new RegExp(
  221.  
    "[`%~!@#$^&=|{}':'\\[\\].<>/?~!@#¥\\\\……&——|{}【】‘:”“'。、?]"
  222.  
    )
  223.  
    if (!str) return false
  224.  
    const flag = Array.from(str).some(item => pattern.test(item))
  225.  
    if (flag) return false
  226.  
    return true
  227.  
    }
  228.  
     
  229.  
    // 下划线转换驼峰
  230.  
    function toHump(name) {
  231.  
    return name.replace(/\_(\w)/g, function(all, letter) {
  232.  
    return letter.toUpperCase()
  233.  
    })
  234.  
    }
  235.  
    // 驼峰转换下划线
  236.  
    function toLine(name) {
  237.  
    return name.replace(/([A-Z])/g, '_$1').toLowerCase()
  238.  
    }
  239.  
     
  240.  
    // 检查特殊字符
  241.  
    function specialCharactersCheck(str) {
  242.  
    const pattern = new RegExp(
  243.  
    "[`%~!@#$^&=|{}':'\\[\\].<>/?~!@#¥\\\\……&——|{}【】‘:”“'。、?]"
  244.  
    )
  245.  
    if (!str) return false
  246.  
    const flag = Array.from(str).some(item => pattern.test(item))
  247.  
    if (flag) return false
  248.  
    return true
  249.  
    }
学新通

10、判断两个对象的值是否相等

  1.  
    // 判断两个对象的值是否相等
  2.  
    function diffObject(obj1, obj2) {
  3.  
    const keys1 = Object.keys(obj1)
  4.  
    const keys2 = Object.keys(obj2)
  5.  
    // console.log(JSON.stringify(keys1), "keys1");
  6.  
    // console.log(JSON.stringify(keys2), "keys2");
  7.  
    if (keys1.length !== keys2.length) {
  8.  
    // //console.log(keys1.length);
  9.  
    // //console.log(keys2.length);
  10.  
    // //
  11.  
    return false
  12.  
    } else {
  13.  
    for (const key in obj1) {
  14.  
    if (!obj2.hasOwnProperty(key)) {
  15.  
    return false
  16.  
    }
  17.  
    // 类型相同
  18.  
    if (typeof obj1[key] === typeof obj2[key]) {
  19.  
    // 同为引用类型
  20.  
    if (typeof obj1[key] === 'object' && typeof obj2[key] === 'object') {
  21.  
    if (obj1[key] !== null && obj2[key] !== null) {
  22.  
    const equal = diffObject(obj1[key], obj2[key])
  23.  
    if (!equal) {
  24.  
    // console.log(key, obj1[key], obj2[key]);
  25.  
    // //
  26.  
    return false
  27.  
    }
  28.  
    }
  29.  
    }
  30.  
    // 同为基础数据类型
  31.  
    if (
  32.  
    typeof obj1[key] !== 'object' &&
  33.  
    typeof obj2[key] !== 'object' &&
  34.  
    obj1[key] !== obj2[key]
  35.  
    ) {
  36.  
    // console.log(key, obj1[key], obj2[key]);
  37.  
    // //
  38.  
    return false
  39.  
    }
  40.  
    } else {
  41.  
    // console.log(key, obj1[key], obj2[key]);
  42.  
    if (
  43.  
    (obj1[key] === null && obj2[key] === undefined) ||
  44.  
    (obj2[key] === null && obj1[key] === undefined)
  45.  
    ) {
  46.  
    // 如果值为null和undefind则认为是相等的
  47.  
    return true
  48.  
    }
  49.  
    // //
  50.  
    return false
  51.  
    }
  52.  
    }
  53.  
    }
  54.  
    return true
  55.  
    }
学新通

11、接口返回的是对象,转换成数组

  1.  
    /**
  2.  
    *
  3.  
    * 数据字典接口返回的是对象
  4.  
    * 将对象转为数组[{code: '', value: []}] 结构
  5.  
    */
  6.  
    function objTransArray(obj) {
  7.  
    const arr = []
  8.  
    if (typeOf(obj) !== 'object') {
  9.  
    return false
  10.  
    } else {
  11.  
    for (const [key, value] of Object.entries(obj)) {
  12.  
    arr.push({ code: key, name: value })
  13.  
    }
  14.  
    return arr
  15.  
    }
  16.  
    }
学新通

12、数组元素为对象,根据元素的某个属性分类

  1.  
    /**
  2.  
    * 数组根据某个属性分组
  3.  
    * @param {*} list 需要分组的数组
  4.  
    * @param {*} groupId 需要分组的数组的属性
  5.  
    * @return {Array} list
  6.  
    */
  7.  
    function arrayGroupBy(list, groupId) {
  8.  
    const sorted = groupBy(list, function(item) {
  9.  
    return [item[groupId]]
  10.  
    })
  11.  
    return sorted
  12.  
    }
  13.  
    function groupBy(arr, fn) {
  14.  
    const groups = {}
  15.  
    arr.forEach(function(val) {
  16.  
    var group = JSON.stringify(fn(val))
  17.  
    groups[group] = groups[group] || []
  18.  
    groups[group].push(val)
  19.  
    })
  20.  
    return Object.keys(groups).map(function(group) {
  21.  
    return groups[group]
  22.  
    })
  23.  
    }
学新通

13、和日期有关

  1.  
    /**
  2.  
    *获取当前日期
  3.  
    * @param {*} type 返回数据的类型 是否包含 具体哪一天
  4.  
    */
  5.  
    function currentDate(type) {
  6.  
    var myDate = new Date()
  7.  
    var tYear = myDate.getFullYear()
  8.  
    var tMonth = myDate.getMonth()
  9.  
    var m = tMonth 1
  10.  
    if (m.toString().length == 1) {
  11.  
    m = '0' m
  12.  
    }
  13.  
    if (type === 'yearMonth') {
  14.  
    return tYear '-' m
  15.  
    }
  16.  
    if (type === 'yearMonthDay') {
  17.  
    var tDay = myDate.getDate()
  18.  
    if (tDay.toString().length == 1) {
  19.  
    tDay = '0' tDay
  20.  
    }
  21.  
    return tYear '-' m '-' tDay
  22.  
    }
  23.  
    }
  24.  
    /**
  25.  
    *获取几个月前的输入日期
  26.  
    *@param {*} date 输入日期(YYYY-MM-DD)
  27.  
    *@param {*} monthNum 需要获取传入日期之前的月数
  28.  
    *@param {*} type 返回数据的类型 是否包含 具体哪一天
  29.  
    *@return {string} string
  30.  
    */
  31.  
    function getPreMonthDay(date, monthNum, type) {
  32.  
    var dateArr = date.split('-')
  33.  
    var year = dateArr[0] // 获取当前日期的年份
  34.  
    var month = dateArr[1] // 获取当前日期的月份
  35.  
    var day = dateArr[2] // 获取当前日期的日
  36.  
    // var days = new Date(year, month, 0)
  37.  
    // days = days.getDate() // 获取当前日期中月的天数
  38.  
    var year2 = year
  39.  
    var month2 = parseInt(month) - monthNum
  40.  
    if (month2 <= 0) {
  41.  
    var absM = Math.abs(month2)
  42.  
    year2 = parseInt(year2) - Math.ceil(absM / 12 == 0 ? 1 : parseInt(absM) / 12)
  43.  
    month2 = 12 - (absM % 12)
  44.  
    }
  45.  
    var day2 = day // 传入的date的日
  46.  
    var days2 = new Date(year2, month2, 0).getDate() // 获取到的月份的最后一天日
  47.  
    if (day2 > days2) {
  48.  
    day2 = days2
  49.  
    }
  50.  
    if (month2 < 10) {
  51.  
    month2 = '0' month2
  52.  
    }
  53.  
    if (type) {
  54.  
    return year2 '-' month2
  55.  
    }
  56.  
    return year2 '-' month2 '-' day2
  57.  
    }
  58.  
    /**
  59.  
    *获取下几个月的输入日期
  60.  
    *@param {*} date 输入日期(YYYY-MM-DD)
  61.  
    *@param {*} monthNum 需要获取传入日期下几个月的月数
  62.  
    *@return {string} string
  63.  
    */
  64.  
    function getNextMonthDay(date, monthNum, type) {
  65.  
    var dateArr = date.split('-')
  66.  
    var year = dateArr[0] // 获取当前日期的年份
  67.  
    var month = dateArr[1] // 获取当前日期的月份
  68.  
    var day = dateArr[2] // 获取当前日期的日
  69.  
    // var days = new Date(year, month, 0)
  70.  
    // days = days.getDate() // 获取当前日期中的月的天数
  71.  
    var year2 = year
  72.  
    var month2 = parseInt(month) parseInt(monthNum)
  73.  
    if (month2 > 12) {
  74.  
    year2 = parseInt(year2) parseInt((parseInt(month2) / 12 == 0 ? 1 : parseInt(month2) / 12))
  75.  
    month2 = parseInt(month2) % 12
  76.  
    }
  77.  
    var day2 = day // 传入的date的日
  78.  
    var days2 = new Date(year2, month2, 0).getDate() // 获取到的月份的最后一天日
  79.  
    if (day2 > days2) {
  80.  
    day2 = days2
  81.  
    }
  82.  
    if (month2 < 10) {
  83.  
    month2 = '0' month2
  84.  
    }
  85.  
    if (type) {
  86.  
    return year2 '-' month2
  87.  
    }
  88.  
    return year2 '-' month2 '-' day2
  89.  
    }
  90.  
    /**
  91.  
    * 获取当前旬的前pre旬和后next旬
  92.  
    * @param {*} pre 当前旬的前pre旬
  93.  
    * @param {*} next 当前旬的后next旬
  94.  
    * @param {*} currentXun 当前旬
  95.  
    * @returns {Array} 当前pre旬和当前旬,加上当前旬的后next旬的数组
  96.  
    */
  97.  
    function getFrontAndBackXun(pre, next, currentXun) {
  98.  
    // 获取echart的x轴时间范围,当前月份的前三个月和后两个月时间
  99.  
    const preTimeRange = []
  100.  
    let currentTimeRange = []
  101.  
    const nextTimeRange = []
  102.  
    const allDateArr = []
  103.  
    currentTimeRange = [1, 2, 3].map(item => {
  104.  
    return currentDate('yearMonth') '-' item
  105.  
    })
  106.  
    for (let i = Math.ceil(pre / 3); i > 0; i--) {
  107.  
    preTimeRange.push([1, 2, 3].map(item => getPreMonthDay(currentDate('yearMonth'), i, 'yearMonth') '-' item))
  108.  
    }
  109.  
    for (let i = 1; i < Math.ceil(next / 3) 1; i ) {
  110.  
    nextTimeRange.push([1, 2, 3].map(item => getNextMonthDay(currentDate('yearMonth'), i, 'yearMonth') '-' item))
  111.  
    }
  112.  
    [...preTimeRange, ...currentTimeRange, ...nextTimeRange].forEach(item => {
  113.  
    if (typeOf(item) === 'array') {
  114.  
    item.forEach(e => { allDateArr.push(e) })
  115.  
    } else {
  116.  
    allDateArr.push(item)
  117.  
    }
  118.  
    })
  119.  
    let checkedMonthRange = []
  120.  
    const index = allDateArr.findIndex(item => item === currentXun)
  121.  
    // 始终保持当前旬的前pre旬和后next旬
  122.  
    checkedMonthRange = allDateArr.slice(index - pre, index next 1)
  123.  
    return checkedMonthRange
  124.  
    }
  125.  
    /**
  126.  
    * 计算两个日期之间的天数
  127.  
    * @param dateString1 开始日期 yyyy-MM-dd
  128.  
    * @param dateString2 结束日期 yyyy-MM-dd
  129.  
    * @returns {number} 如果日期相同 返回一天 开始日期大于结束日期,返回0
  130.  
    */
  131.  
    function getDaysBetween(dateString1, dateString2) {
  132.  
    var startDate = Date.parse(dateString1)
  133.  
    var endDate = Date.parse(dateString2)
  134.  
    if (startDate > endDate) {
  135.  
    return 0
  136.  
    }
  137.  
    if (startDate == endDate) {
  138.  
    return 1
  139.  
    }
  140.  
    var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000)
  141.  
    return days
  142.  
    }
  143.  
    /**
  144.  
    * 时间控件按月份统计 开始日期为当月的第一天 结束日期为当月的最后一天
  145.  
    * @param date 日期区间 [yyyy-MM, yyyy-MM]
  146.  
    * @returns {Array} 返回 [yyyy-MM-dd, yyyy-MM-dd]
  147.  
    */
  148.  
    function exportDateRange(date) {
  149.  
    const datertArr = date[0].split('-')
  150.  
    const start = datertArr[0] '-' datertArr[1] '-' '01'
  151.  
    const endArr = date[1].split('-')
  152.  
    const end = endArr[0] '-' endArr[1] '-' new Date(endArr[0], endArr[1], 0).getDate()
  153.  
    return [start, end]
  154.  
    }
  155.  
     
  156.  
    /**
  157.  
    * 获取两个时间日期之间所有的日期
  158.  
    * @param stime 开始日期
  159.  
    * @param etime 结束日期
  160.  
    * @returns {Array} 返回所有时间组成的数组
  161.  
    */
  162.  
    function getdiffdate(stime, etime) {
  163.  
    // 初始化日期列表,数组
  164.  
    const diffdate = []
  165.  
    let i = 0
  166.  
    // 开始日期小于等于结束日期,并循环
  167.  
    while (stime <= etime) {
  168.  
    diffdate[i] = stime
  169.  
    // 获取开始日期时间戳
  170.  
    const stime_ts = new Date(stime).getTime()
  171.  
    // console.log('当前日期:' stime '当前时间戳:' stime_ts)
  172.  
    // 增加一天时间戳后的日期
  173.  
    const next_date = stime_ts (24 * 60 * 60 * 1000)
  174.  
    // 拼接年月日,这里的月份会返回(0-11),所以要 1
  175.  
    const next_dates_y = new Date(next_date).getFullYear() '-'
  176.  
    const next_dates_m = (new Date(next_date).getMonth() 1 < 10) ? '0' (new Date(next_date).getMonth() 1) '-' : (new Date(next_date).getMonth() 1) '-'
  177.  
    const next_dates_d = (new Date(next_date).getDate() < 10) ? '0' new Date(next_date).getDate() : new Date(next_date).getDate()
  178.  
    stime = next_dates_y next_dates_m next_dates_d
  179.  
    // 增加数组key
  180.  
    i
  181.  
    }
  182.  
    return diffdate
  183.  
    }
  184.  
     
  185.  
    /**
  186.  
    * 获取该日期在当年第几周
  187.  
    * @param date 测算时间
  188.  
    * @returns {Number} 返回当年的第几周
  189.  
    */
  190.  
    function weekOfYear(date) {
  191.  
    const year = date.split('-')[0]
  192.  
    const month = date.split('-')[1]
  193.  
    const day = date.split('-')[2]
  194.  
    let date1 = new Date(year, 0, 1)
  195.  
    let date2 = new Date(year, month - 1, day, 1)
  196.  
    const dayMS = 24 * 60 * 60 * 1000
  197.  
    // 每周从周一开始 8
  198.  
    const firstDay = (8 - date1.getDay()) * dayMS
  199.  
    const weekMS = 7 * dayMS
  200.  
    date1 = date1.getTime()
  201.  
    date2 = date2.getTime()
  202.  
    return Math.ceil((date2 - date1 - firstDay) / weekMS) 1
  203.  
    }
  204.  
    /**
  205.  
    * 获取当前日期前后N天的日期
  206.  
    * @param dayCount 前后的天数
  207.  
    * @returns {String} 返回具体的日期
  208.  
    */
  209.  
    function getDateStr(dayCount) {
  210.  
    var today = new Date()
  211.  
    today.setDate(today.getDate() dayCount) // 获取AddDayCount天后的日期
  212.  
    var y = today.getFullYear()
  213.  
    var m = (today.getMonth() 1) < 10 ? '0' (today.getMonth() 1) : (today.getMonth() 1) // 获取当前月份的日期,不足10补0
  214.  
    var d = today.getDate() < 10 ? '0' today.getDate() : today.getDate() // 获取当前几号,不足10补0
  215.  
    return y '-' m '-' d
  216.  
    }
  217.  
     
  218.  
    /**
  219.  
    * 普通日期时间格式转换
  220.  
    * @param val 原日期时间
  221.  
    * @param type 转换成的类型
  222.  
    * @returns {String} 换换成对应的日期格式
  223.  
    */
  224.  
    function changeMonth(val, type) {
  225.  
    const month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  226.  
    if (val) {
  227.  
    if (!type) { // 不传类型 默认转换成 日-月
  228.  
    const arr = parseTime(val, '{m}-{d}').split('-')
  229.  
    return `${arr[1]}-${month[ arr[0] - 1]}`
  230.  
    }
  231.  
    if (type === 'mdhi') { // 转换成 月-日 时:分
  232.  
    const arr = parseTime(val, '{m}-{d} {h}:{i}').split(' ') // 月 天 时 分
  233.  
    const dateArr = arr[0].split('-')
  234.  
    return `${dateArr[1]}-${month[ dateArr[0] - 1]} ${arr[1]}`
  235.  
    }
  236.  
    if (type === 'm') { // 转换成 月
  237.  
    const arr = val.split('-')
  238.  
    return `${month[ arr[1] - 1]}`
  239.  
    }
  240.  
    if (/^sem/.test(type)) {
  241.  
    const arr = val.split('-')
  242.  
    const y = arr[0] // 年
  243.  
    const m = arr[1] // 月
  244.  
    const x = arr[2] // 旬
  245.  
    if (x == 1) {
  246.  
    return '01-10/' month[ m - 1] (type.includes('y') ? '/' y : '')
  247.  
    } else if (x == 2) {
  248.  
    return '11-20/' month[ m - 1] (type.includes('y') ? '/' y : '')
  249.  
    } else {
  250.  
    return '21-' new Date(y, m, 0).getDate() '/' month[ m - 1] (type.includes('y') ? '/' y : '')
  251.  
    }
  252.  
    }
  253.  
    }
  254.  
    return ''
  255.  
    }
  256.  
    /**
  257.  
    * 月份转换 数字<=>英文缩写
  258.  
    * @param val 需要转换的月份值
  259.  
    * @param type 转换成的类型
  260.  
    * @returns {String} 转换成对应的月份格式
  261.  
    */
  262.  
    function translateMonth(val, type) {
  263.  
    const enMonth = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  264.  
    const numMonth = { 'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', 'May': '05', 'Jun': '06', 'Jul': '07', 'Aug': '08', 'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12' }
  265.  
    switch (type) {
  266.  
    case 'toEn': // 转换成英文缩写
  267.  
    return `${enMonth[ val - 1]}`
  268.  
    case 'toNum': // 转换成数字月份
  269.  
    return `${numMonth[val]}`
  270.  
    }
  271.  
    }
  272.  
     
  273.  
    /**
  274.  
    * 根据当年当月第几旬获取的日期范围 2021-07-3 => {startDate: 2021-07-21, endDate: 2021-07-31}
  275.  
    * @param year 年份
  276.  
    * @param month 月份
  277.  
    * @param decade 旬
  278.  
    * @returns {String} 返回补0后的结果或者直接返回
  279.  
    */
  280.  
    function decadeToDate(year, month, decade) {
  281.  
    switch (decade) {
  282.  
    case 1:
  283.  
    return {
  284.  
    startDate: year '-' month '-' '01',
  285.  
    endDate: year '-' month '-' '10'
  286.  
    }
  287.  
    case 2:
  288.  
    return {
  289.  
    startDate: year '-' month '-' '11',
  290.  
    endDate: year '-' month '-' '20'
  291.  
    }
  292.  
    case 3:
  293.  
    return {
  294.  
    startDate: year '-' month '-' '21',
  295.  
    endDate: year '-' month '-' new Date(year, month, 0).getDate()
  296.  
    }
  297.  
    }
  298.  
    }
  299.  
    /**
  300.  
    * 根据当前日期中的‘日’翻译成处于第几旬
  301.  
    * @param day 日
  302.  
    * @returns {Number} 返回第几旬
  303.  
    */
  304.  
    function getDecade(day) {
  305.  
    if (day < 11) {
  306.  
    return 1
  307.  
    } else if (day < 21) {
  308.  
    return 2
  309.  
    } else {
  310.  
    return 3
  311.  
    }
  312.  
    }
  313.  
    /**
  314.  
    * 根据传入的日期范围获取所有的日期 按旬 或者按月
  315.  
    * @param range 日期范围
  316.  
    * @param type 返回的类型 按旬 还是按月
  317.  
    * @returns {Array} 返回所有的传入日期范围之内的日期
  318.  
    */
  319.  
    function getDateRange(range, type) {
  320.  
    const formatManthRange = []
  321.  
    let arr = []
  322.  
    // 拿到时间日期的所有值,对月份不是两位数的月份进行前面补'0'操作
  323.  
    const monthRange = getMonthBetween(range).map(item => {
  324.  
    if (item.split('-')[1].length < 2) {
  325.  
    return item.split('-')[0] '-' '0' item.split('-')[1]
  326.  
    } else {
  327.  
    return item
  328.  
    }
  329.  
    })
  330.  
    if (type == 0) {
  331.  
    // 每个月按三旬组合而成的数组当成另一个数组的元素
  332.  
    arr = monthRange.map(item => {
  333.  
    return [1, 2, 3].map(sonItem => item '-' sonItem)
  334.  
    })
  335.  
    arr.forEach(item => {
  336.  
    if (typeOf(item) === 'array') {
  337.  
    item.forEach(e => {
  338.  
    formatManthRange.push(e)
  339.  
    })
  340.  
    } else {
  341.  
    formatManthRange.push(item)
  342.  
    }
  343.  
    })
  344.  
    return formatManthRange
  345.  
    } else {
  346.  
    return monthRange
  347.  
    }
  348.  
    }
  349.  
    /**
  350.  
    * 根据传入的日期范围获取所有的日期 处理年份是否同一年或者跨度是否大于一年
  351.  
    * @param dateRange 日期范围
  352.  
    * @returns {Array} 返回所有的传入日期范围之内的日期
  353.  
    */
  354.  
    // 根据时间日期控件的时间设置好横坐标时间日期范围区间
  355.  
    function getMonthBetween(dateRange) {
  356.  
    const result1 = []
  357.  
    const result2 = []
  358.  
    const result3 = []
  359.  
    let result = []
  360.  
    const start = dateRange[0].split('-')
  361.  
    const end = dateRange[1].split('-')
  362.  
    if (start[0] < end[0]) { // 如果开始时间日期的年份和结束时间日期的年份 不是 同一年
  363.  
    for (let i = start[1]; i < 13; i ) {
  364.  
    result1.push(start[0] '-' i)
  365.  
    }
  366.  
    for (let i = 1; i <= end[1]; i ) {
  367.  
    result2.push(end[0] '-' i)
  368.  
    }
  369.  
    if ( end[0] - start[0] > 1) {
  370.  
    // 证明相差不只一年
  371.  
    for (let i = start[0] 1; i < end[0] - start[0]; i ) {
  372.  
    for (let j = 1; j < 13; j ) {
  373.  
    result3.push(i '-' j)
  374.  
    }
  375.  
    }
  376.  
    }
  377.  
    result = [...result1, ...result3, ...result2]
  378.  
    } else { // 如果开始时间日期的年份和结束时间日期的年份 是 同一年
  379.  
    for (let i = start[1]; i <= end[1]; i ) {
  380.  
    result.push(start[0] '-' i)
  381.  
    }
  382.  
    }
  383.  
    return result
  384.  
    }
  385.  
    /**
  386.  
    * 获取当前月份的前后几个月的日期
  387.  
    * @param before 前几个月
  388.  
    * @param after 后几个月
  389.  
    * @returns {Array} 返回所有的日期范围
  390.  
    */
  391.  
    function getMonthBeAfRange(before, after) {
  392.  
    const arr = []
  393.  
    let recentTimeRange = []
  394.  
    const preTimeRange = []
  395.  
    const nextTimeRange = []
  396.  
    // 获取echart的x轴时间范围,当前月份的前三个月和后两个月时间
  397.  
    recentTimeRange = [1, 2, 3].map(item => {
  398.  
    return currentDate('yearMonth') '-' item
  399.  
    })
  400.  
    for (let i = before; i > 0; i--) {
  401.  
    preTimeRange.push([1, 2, 3].map(item => getPreMonthDay(currentDate('yearMonth'), i, 'yearMonth') '-' item))
  402.  
    }
  403.  
    for (let i = 1; i < after 1; i ) {
  404.  
    nextTimeRange.push([1, 2, 3].map(item => getNextMonthDay(currentDate('yearMonth'), i, 'yearMonth') '-' item))
  405.  
    }
  406.  
    [...preTimeRange, ...recentTimeRange, ...nextTimeRange].forEach(item => {
  407.  
    if (typeOf(item) === 'array') {
  408.  
    item.forEach(e => {
  409.  
    arr.push(e)
  410.  
    })
  411.  
    } else {
  412.  
    arr.push(item)
  413.  
    }
  414.  
    })
  415.  
    return arr
  416.  
    }
  417.  
     
  418.  
    /**
  419.  
    * Parse the time to string
  420.  
    * @param {(Object|string|number)} time
  421.  
    * @param {string} cFormat
  422.  
    * @returns {string | null}
  423.  
    */
  424.  
    export function parseTime(time, cFormat) {
  425.  
    if (arguments.length === 0) {
  426.  
    return null
  427.  
    }
  428.  
    if (!time) {
  429.  
    return null
  430.  
    }
  431.  
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  432.  
    let date
  433.  
    if (typeof time === 'object') {
  434.  
    date = time
  435.  
    } else {
  436.  
    if ((typeof time === 'string') && (/^[0-9] $/.test(time))) {
  437.  
    time = parseInt(time)
  438.  
    }
  439.  
    if ((typeof time === 'number') && (time.toString().length === 10)) {
  440.  
    time = time * 1000
  441.  
    }
  442.  
    date = new Date(time)
  443.  
    }
  444.  
    const formatObj = {
  445.  
    y: date.getFullYear(),
  446.  
    m: date.getMonth() 1,
  447.  
    d: date.getDate(),
  448.  
    h: date.getHours(),
  449.  
    i: date.getMinutes(),
  450.  
    s: date.getSeconds(),
  451.  
    a: date.getDay()
  452.  
    }
  453.  
    const time_str = format.replace(/{([ymdhisa]) }/g, (result, key) => {
  454.  
    const value = formatObj[key]
  455.  
    // Note: getDay() returns 0 on Sunday
  456.  
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
  457.  
    return value.toString().padStart(2, '0')
  458.  
    })
  459.  
    return time_str
  460.  
    }
学新通

14、元素为对象的数组根据元素对象某个属性排序

  1.  
    /**
  2.  
    * 元素为对象的数组根据元素对象某个属性排序
  3.  
    * @param arr 原数组
  4.  
    * @param prop 原数组的元素的某个属性
  5.  
    * @param orderByType 按倒序还是顺序
  6.  
    * @returns {Array} 返回排好序的数组
  7.  
    */
  8.  
    function arrayObjSort(arr, prop, orderByType) {
  9.  
    return arr.sort(compare(prop, orderByType))
  10.  
    }
  11.  
    function compare(prop, orderByType) {
  12.  
    return function(obj1, obj2) {
  13.  
    var val1 = obj1[prop]
  14.  
    var val2 = obj2[prop]
  15.  
    if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
  16.  
    val1 = Number(val1)
  17.  
    val2 = Number(val2)
  18.  
    }
  19.  
    switch (orderByType) {
  20.  
    // 倒序
  21.  
    case 'desc':
  22.  
    if (val1 > val2) {
  23.  
    return -1
  24.  
    } else if (val1 < val2) {
  25.  
    return 1
  26.  
    } else {
  27.  
    return 0
  28.  
    }
  29.  
    // 升序
  30.  
    case 'asc':
  31.  
    if (val1 < val2) {
  32.  
    return -1
  33.  
    } else if (val1 > val2) {
  34.  
    return 1
  35.  
    } else {
  36.  
    return 0
  37.  
    }
  38.  
    }
  39.  
    }
  40.  
    }
学新通

15、下载文件接口封装

  1.  
    /**
  2.  
    * 下载文件
  3.  
    * @param {data} 相关下载的数据
  4.  
    * @param {name} 下载文件的名字
  5.  
    */
  6.  
    export function downloadFile(data, name, suffix) {
  7.  
    const url = window.URL.createObjectURL(data)
  8.  
    const link = document.createElement('a')
  9.  
    link.style.display = 'none'
  10.  
    link.href = url
  11.  
    const fileName = name
  12.  
    link.setAttribute('download', fileName)
  13.  
    document.body.appendChild(link)
  14.  
    link.click()
  15.  
    URL.revokeObjectURL(link.href)
  16.  
    document.body.removeChild(link)
  17.  
    }
  18.  
     
学新通

16、导出文件

封装的导出方法如下

  1.  
    async function exportFile(type, params) {
  2.  
    await commonExport({ exportType: type, queryConds: JSON.stringify(params) }).then(res => {
  3.  
    if (res.data) {
  4.  
    const name = res.headers['content-disposition'] ? decodeURI(res.headers['content-disposition'].split(';')[1].split('filename=')[1].replace(/\"/gi, '')) : new Date() '.xls'
  5.  
    if (!name) {
  6.  
    this.$message.error('Download error')
  7.  
    return false
  8.  
    }
  9.  
    const url = window.URL.createObjectURL(res.data)
  10.  
    const link = document.createElement('a')
  11.  
    link.style.display = 'none'
  12.  
    link.href = url
  13.  
    link.setAttribute('download', name)
  14.  
    document.body.appendChild(link)
  15.  
    link.click()
  16.  
    URL.revokeObjectURL(link.href)
  17.  
    document.body.removeChild(link)
  18.  
    }
  19.  
    })
  20.  
    }
学新通

其中的commonExport方法如下

  1.  
    export function commonExport(params) {
  2.  
    return downHttp.get('/common/export', { params })
  3.  
    }
  4.  
     
  5.  
    同接口封装的axios调用类似

上面的downHttp如下

  1.  
    import axios from 'axios'
  2.  
    // import { Message, MessageBox } from 'element-ui'
  3.  
    import store from '@/store'
  4.  
    import { getToken } from '@/utils/auth'
  5.  
     
  6.  
    // function getSaveQueryFlag() {
  7.  
    // const cookieArr = String(document.cookie).split(';')
  8.  
    // cookieArr.forEach((item, index) => {
  9.  
    // if (item.includes('Admin-Token')) {
  10.  
    // cookieArr.splice(index, 1)
  11.  
    // }
  12.  
    // })
  13.  
    // return cookieArr.join(',')
  14.  
    // }
  15.  
    /**
  16.  
    * 下载导出专用
  17.  
    */
  18.  
    const downHttp = axios.create({
  19.  
    responseType: 'blob',
  20.  
    baseURL: process.env.VUE_APP_BASE_API,
  21.  
    timeout: 60 * 1000 // request timeout
  22.  
    })
  23.  
    downHttp.interceptors.request.use(
  24.  
    config => {
  25.  
    if (store.getters.token) {
  26.  
    // config.headers['saveQueryFlag'] = getSaveQueryFlag()
  27.  
    config.headers['Authorization'] = getToken()
  28.  
    }
  29.  
    return config
  30.  
    },
  31.  
    error => {
  32.  
    return Promise.reject(error)
  33.  
    }
  34.  
    )
  35.  
    downHttp.interceptors.response.use(response => {
  36.  
    if (response.status === 200) return response
  37.  
    })
  38.  
     
  39.  
    export default downHttp
学新通

导出文件需要后端配合,里面调用的后端的接口,返回不是json格式数据,这里的方法仅供参考

这样调用

exportFile('cargoList', params)

cargoList这个字符串为同后端约定的,params为调用的获取后台数据接口的参数

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhhaeegj
系列文章
更多 icon
同类精品
更多 icon
继续加载