那些开发中常用的方法 - vue

167 阅读6分钟

1. 根据输入的地址自动获取收件人、联系电话、省市区以及详细地址

import { smartAddress } from '@/utils/addressParse.js';
// 自动获取地址信息
export const utilSmartAddress = smartAddress;

addressParse文件 文献地址 pcasCode.js 链接:pan.baidu.com/s/1WRxDfOWg… 提取码:ot9m

zipCode.js 链接:pan.baidu.com/s/1vRcza7L4… 提取码:y54w

import pcassCode from '@/static/js/pcasCode.js';
import zipCode from '@/static/js/zipCode.js';
var addressList = []; //地址列表
var zipCodeList = []; //邮编列表
//获取地址以及邮编json
addressList = pcassCode;
addressList.forEach((item) => {
  formatAddresList(item, 1, "");
});
zipCodeList = zipCodeFormat(zipCode);

/**
 * 地址数据处理
 * @param addressList-各级数据对象
 * @param index-对应的省/市/县区/街道
 * @param province-只有直辖市会处理为  北京市北京市
 * @returns <array>
 */
function formatAddresList(addressList, index, province) {
  if (index === 1) {
    //省
    addressList.province = addressList.name;
    addressList.type = "province";
  }
  if (index === 2) {
    //市
    if (addressList.name == "市辖区") {
      addressList.name = province.name;
    }
    addressList.city = addressList.name;
    addressList.type = "city";
  }
  if (index === 3) {
    //区或者县
    addressList.county = addressList.name;
    addressList.type = "county";
  }
  if (index === 4) {
    //街道
    addressList.street = addressList.name;
    addressList.type = "street";
  }
  if (addressList.children) {
    index++;
    addressList.children.forEach((res) => {
      formatAddresList(res, index, addressList);
    });
  }
}
/**
 * 解析邮编
 * @param
 * @returns <array>
 */
function zipCodeFormat(zipCode) {
  let list = [];
  zipCode.forEach((el) => {
    if (el.child) {
      el.child.forEach((event) => {
        if (event.child) {
          event.child.forEach((element) => {
            list.push(element.zipcode);
          });
        }
      });
    }
  });
  return list;
}

var smartObj = {};
/**
 * 自动解析地址
 * @param event识别的地址
 * @returns <obj>
 */
export function smartAddress(event) {
  let copy = event;
  let _phone = copy.match(
    /((\d{2,4}[-_-—])\d{3,8}([-_-—]?\d{3,8})?([-_-—]?\d{1,7})?)|(0?1\d{10})/g
  );
  if(_phone && _phone.length>0){
    event = event.replace(_phone[0],'')
  }
  event = stripscript(event); //过滤特殊字符
  let obj = {};
  let copyaddress = JSON.parse(JSON.stringify(event));
  copyaddress = copyaddress.split(" ");

  copyaddress.forEach((res, index) => {
    if (res) {
      if (res.length == 1) {
        res += "XX"; // 过滤掉一位的名字或者地址
      }
      let addressObj = smatrAddress(res);
      obj = Object.assign(obj, addressObj);
      if (JSON.stringify(addressObj) === "{}") {
        obj.name = res.replace("XX", "");
      }
    }
  });

  if (!obj.phone && _phone) {
    _phone.forEach((e) => {
      if (e.length >= 8) {
        obj.phone = e;
      }
    });
  }
  return obj;
}

function smatrAddress(event) {
  smartObj = {};
  let address = event;
  //address=  event.replace(/\s/g, ''); //去除空格
  address = stripscript(address); //过滤特殊字符

  //身份证号匹配
  if (IdentityCodeValid(address)) {
    smartObj.idCard = address;
    address = address.replace(address, "");
  }

  //电话匹配
  let phone = address.match(
    /(86-[1][0-9]{10}) | (86[1][0-9]{10})|([1][0-9]{10})/g
  );
  if (phone) {
    smartObj.phone = phone[0];
    address = address.replace(phone[0], "");
  }

  //邮编匹配
  zipCodeList.forEach((res) => {
    if (address.indexOf(res) != -1) {
      let num = address.indexOf(res);
      let code = address.slice(num, num + 6);
      smartObj.zipCode = code;
      address = address.replace(code, "");
    }
  });
  let matchAddress = "";
  //省匹配 比如输入北京市朝阳区,会用北  北京  北京市 北京市朝 以此类推在addressList里的province中做匹配,会得到北京市  河北省 天津市等等;
  let matchProvince = []; //粗略匹配上的省份
  // for (let begIndex = 0; begIndex < address.length; begIndex++) {
  matchAddress = "";
  for (let endIndex = 0; endIndex < address.length; endIndex++) {
    //  if (endIndex > begIndex) {
    matchAddress = address.slice(0, endIndex + 2);
    addressList.forEach((res) => {
      if (res["province"].indexOf(matchAddress) != -1) {
        matchProvince.push({
          province: res.province,
          provinceCode: res.code,
          matchValue: matchAddress,
        });
      }
    });
    // }
  }
  //  }

  //统计筛选初略统计出的省份
  matchProvince.forEach((res) => {
    res.index = 0;
    matchProvince.forEach((el) => {
      if (res.province == el.province) {
        el.index++;
        if (res.matchValue.length > el.matchValue.length) {
          el.matchValue = res.matchValue;
        }
      }
    });
  });
  if (matchProvince.length != 0) {
    let province = matchProvince.reduce((p, v) => (p.index < v.index ? v : p));
    smartObj.province = province.province;
    smartObj.provinceCode = province.provinceCode;
    address = address.replace(province.matchValue, "");
  }
  //市查找
  let matchCity = []; //粗略匹配上的市
  matchAddress = "";
  for (let endIndex = 0; endIndex < address.length; endIndex++) {
    matchAddress = address.slice(0, endIndex + 2);
    addressList.forEach((el) => {
      //  if (el.name == smartObj.province) {
      if (el.code == smartObj.provinceCode || !smartObj.provinceCode) {
        if (
          smartObj.province == "北京市" ||
          smartObj.province == "天津市" ||
          smartObj.province == "上海市" ||
          smartObj.province == "重庆市"
        ) {
          el.children.forEach((item) => {
            item.children.forEach((res) => {
              if (res["county"].indexOf(matchAddress) != -1) {
                matchCity.push({
                  county: res.county,
                  countyCode: res.code,
                  city: item.city,
                  cityCode: item.code,
                  matchValue: matchAddress,
                  province: el.province,
                  provinceCode: el.code,
                });
              }
            });
          });
        } else {
          el.children.forEach((res) => {
            if (res["city"].indexOf(matchAddress) != -1) {
              matchCity.push({
                city: res.city,
                cityCode: res.code,
                matchValue: matchAddress,
                province: el.province,
                provinceCode: el.code,
              });
            }
          });
        }
      }
      // }
    });
  }

  //统计筛选初略统计出的市
  matchCity.forEach((res) => {
    res.index = 0;
    matchCity.forEach((el) => {
      if (res.city == el.city) {
        el.index++;
        if (res.matchValue.length > el.matchValue.length) {
          el.matchValue = res.matchValue;
        }
      }
    });
  });
  if (matchCity.length != 0) {
    let city = matchCity.reduce((p, v) => (p.index < v.index ? v : p));
    smartObj.city = city.city;
    smartObj.cityCode = city.cityCode;
    smartObj.county = city.county;
    smartObj.countyCode = city.countyCode;
    if (!smartObj.province) {
      smartObj.province = city.province;
      smartObj.provinceCode = city.provinceCode;
    }
    address = address.replace(city.matchValue, "");
  }

  //区县查找
  let matchCounty = []; //粗略匹配上的区县
  matchAddress = "";
  for (let endIndex = 0; endIndex < address.length; endIndex++) {
    matchAddress = address.slice(0, endIndex + 2);
    addressList.forEach((el) => {
      //  if (el.name == smartObj.province) {
      if (
        smartObj.province == "北京市" ||
        smartObj.province == "天津市" ||
        smartObj.province == "上海市" ||
        smartObj.province == "重庆市"
      ) {
        //nothing
      } else {
        el.children.forEach((item) => {
          //  if (item.name == smartObj.city) {
          item.children.forEach((res) => {
            if (res["county"].indexOf(matchAddress) != -1) {
              //省/市  || 省
              if (smartObj.province) {
                if (res.code.slice(0, 4) == smartObj.cityCode) {
                  matchCounty.push({
                    county: res.county,
                    countyCode: res.code,
                    city: item.city,
                    cityCode: item.code,
                    matchValue: matchAddress,
                    province: el.province,
                    provinceCode: el.code,
                  });
                }
              } else if (!smartObj.province && !smartObj.city) {
                matchCounty.push({
                  county: res.county,
                  countyCode: res.code,
                  city: item.city,
                  cityCode: item.code,
                  matchValue: matchAddress,
                  province: el.province,
                  provinceCode: el.code,
                });
              }
            }
          });
          //  }
        });
      }
      //  }
    });
  }
  //统计筛选初略统计出的区县
  matchCounty.forEach((res) => {
    res.index = 0;
    matchCounty.forEach((el) => {
      if (res.city == el.city) {
        el.index++;
        if (res.matchValue.length > el.matchValue.length) {
          el.matchValue = res.matchValue;
        }
      }
    });
  });
  if (matchCounty.length != 0) {
    let city = matchCounty.reduce((p, v) => (p.index < v.index ? v : p));
    smartObj.county = city.county;
    smartObj.countyCode = city.countyCode;
    if (!smartObj.province) {
      smartObj.province = city.province;
      smartObj.provinceCode = city.provinceCode;
    }
    if (!smartObj.city) {
      smartObj.city = city.city;
      smartObj.cityCode = city.cityCode;
    }
    address = address.replace(city.matchValue, "");
  }

  //街道查找
  let matchStreet = []; //粗略匹配上的街道查
  matchAddress = "";
  for (let endIndex = 0; endIndex < address.length; endIndex++) {
    matchAddress = address.slice(0, endIndex + 3);
    addressList.forEach((el) => {
      if (el.name == smartObj.province) {
        if (
          smartObj.province == "北京市" ||
          smartObj.province == "天津市" ||
          smartObj.province == "上海市" ||
          smartObj.province == "重庆市"
        ) {
          //nothing
        } else {
          el.children.forEach((element) => {
            if (element.name == smartObj.city) {
              element.children.forEach((item) => {
                if (item.name == smartObj.county) {
                  item.children.forEach((res) => {
                    if (res["street"].indexOf(matchAddress) != -1) {
                      matchStreet.push({
                        street: res.street,
                        streetCode: res.code,
                        matchValue: matchAddress,
                      });
                    }
                  });
                }
              });
            }
          });
        }
      }
    });
  }

  //统计筛选初略统计出的区县
  matchStreet.forEach((res) => {
    res.index = 0;
    matchStreet.forEach((el) => {
      if (res.city == el.city) {
        el.index++;
        if (res.matchValue.length > el.matchValue.length) {
          el.matchValue = res.matchValue;
        }
      }
    });
  });

  if (matchStreet.length != 0) {
    let city = matchStreet.reduce((p, v) => (p.index < v.index ? v : p));
    smartObj.street = city.street;
    smartObj.streetCode = city.streetCode;
    address = address.replace(city.matchValue, "");
  }
  //姓名查找
  if (smartObj.province) {
    smartObj.address = address;
  }

  return smartObj;
}
//过滤特殊字符
function stripscript(s) {
  s = s.replace(/(\d{3})-(\d{4})-(\d{4})/g, "$1$2$3");
  s = s.replace(/(\d{3}) (\d{4}) (\d{4})/g, "$1$2$3");
  var pattern = new RegExp(
    "[`~!@#$^&*()=|{}':;',\\[\\].<>/?~!@#¥……&*()——|{}【】‘;:”“’。,、?-]"
  );
  var rs = "";
  for (var i = 0; i < s.length; i++) {
    rs = rs + s.substr(i, 1).replace(pattern, " ");
  }
  rs = rs.replace(/[\r\n]/g, "");
  return rs;
}

function IdentityCodeValid(code) {
  let pass;
  var city = {
    11: "北京",
    12: "天津",
    13: "河北",
    14: "山西",
    15: "内蒙古",
    21: "辽宁",
    22: "吉林",
    23: "黑龙江 ",
    31: "上海",
    32: "江苏",
    33: "浙江",
    34: "安徽",
    35: "福建",
    36: "江西",
    37: "山东",
    41: "河南",
    42: "湖北 ",
    43: "湖南",
    44: "广东",
    45: "广西",
    46: "海南",
    50: "重庆",
    51: "四川",
    52: "贵州",
    53: "云南",
    54: "西藏 ",
    61: "陕西",
    62: "甘肃",
    63: "青海",
    64: "宁夏",
    65: "新疆",
    71: "台湾",
    81: "香港",
    82: "澳门",
    91: "国外 ",
  };
  var tip = "";
  pass = true;

  if (!code || !/^\d{17}(\d|X)$/i.test(code)) {
    tip = "身份证号格式错误";
    pass = false;
  } else if (!city[code.substr(0, 2)]) {
    tip = "地址编码错误";
    pass = false;
  } else {
    //18位身份证需要验证最后一位校验位
    if (code.length == 18) {
      code = code.split("");
      //∑(ai×Wi)(mod 11)
      //加权因子
      var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
      //校验位
      var parity = [1, 0, "X", 9, 8, 7, 6, 5, 4, 3, 2];
      var sum = 0;
      var ai = 0;
      var wi = 0;
      for (var i = 0; i < 17; i++) {
        ai = code[i];
        wi = factor[i];
        sum += ai * wi;
      }
      var last = parity[sum % 11];
      if (parity[sum % 11] != code[17]) {
        tip = "校验位错误";
        pass = false;
      }
    }
  }
  return pass;
}

使用

<template>
    <el-form-item
        label="添加方式"
        prop="userDef4"
        :rules="[
            {
                required: true,
                message: '必填项不能为空!',
                trigger: 'change',
            },
        ]">
        <el-select v-model="formData.userDef4" filterable placeholder="请选择" @change="addTypeChange">
            <el-option label="新增收货人" value="1" />
        </el-select>
    </el-form-item>
    <template>
        <el-space wrap :size="20" alignment="flex-start">
            <div>
                <el-form-item
                    label="收货人"
                    prop="ship_to_attention_to"
                    :rules="[
                        {
                            required: true,
                            message: '必填项不能为空!',
                            trigger: 'change'
                        }
                    ]">
                    <el-input v-model="formData.ship_to_attention_to" placeholder="请输入" />
                </el-form-item>
                <el-form-item
                    label="联系电话"
                    prop="ship_to_mobile"
                    :rules="[
                        {
                            required: true,
                            message: '必填项不能为空!',
                            trigger: 'change'
                        }
                    ]">
                    <el-input v-model="formData.ship_to_mobile" placeholder="请输入" />
                </el-form-item>
                <el-form-item
                    label="收货省区"
                    prop="consigneeProvinces"
                    :rules="[
                        {
                            required: true,
                            message: '必填项不能为空!',
                            trigger: 'change'
                        }
                    ]">
                    <el-cascader
                        v-model="formData.consigneeProvinces"
                        :options="provinceList"
                        @change="handleProvincesChange"
                        filterable
                        :props="{ label: 'name', value: 'name' }" />
                </el-form-item>
                <el-form-item
                    label="详细地址"
                    prop="ship_to_address"
                    :rules="[
                        {
                            required: true,
                            message: '必填项不能为空!',
                            trigger: 'change'
                        }
                    ]">
                    <el-input
                        v-model="formData.ship_to_address"
                        placeholder="请输入"
                        maxlength="1000"
                        show-word-limit
                        type="textarea" />
                </el-form-item>
            </div>
            <div>
                <el-form-item label="" label-width="0px">
                    <div class="dotted-line">
                    <el-input
                        v-model="consigneePasteAddress"
                        rows="8"
                        placeholder="粘贴收件人姓名、电话、地址"
                        type="textarea" />
                        <div>
                            <el-button type="text" @click="handleConsigneeSmart" :disabled="!consigneePasteAddress">自动添加地址</el-button>
                        </div>
                    </div>
                </el-form-item>
            </div>
        </el-space>
    </template>
</template>
<script lang="ts" setup>
import { utilSmartAddress } from '@/utils';
const handleConsigneeSmart = () => {
    const result = utilSmartAddress(state.consigneePasteAddress) || {};
    if (result.name) {
        state.formData.ship_to_attention_to = result.name;
    }
    let _arr: Array<string> = [];
    if (result.province) {
        state.formData.ship_to_state_name = result.province;
        _arr.push(result.province);
    }
    if (result.city) {
        state.formData.ship_to_city_name = result.city;
        _arr.push(result.city);
    }
    if (result.county) {
        state.formData.ship_to_district_name = result.county;
        _arr.push(result.county);
    }
    state.formData.consigneeProvinces = _arr;

    if (result.address) {
        state.formData.ship_to_address = result.address;
    }

    if (result.phone) {
        state.formData.ship_to_mobile = result.phone;
    }
    if (result.zipCode) {
        state.formData.consigneePostCode = result.zipCode;
    }
};
</script>

2. 检查金额输入

export const utilCheckAmount = (e: any): number => {
    let newValue = e;
    if (newValue.indexOf('.') === 0) {
        newValue = '0' + newValue;
    }
    newValue = newValue.replace(/[^\d.]/g, ''); //清除“数字”和“.”以外的字符
    newValue = newValue.replace(/\.{2,}/g, '.'); //只保留第一个. 清除多余的
    newValue = newValue.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
    newValue = newValue.replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
    /*整数不能大于14位*/
    if (newValue.length > 14) {
        newValue = '99999999999999.99';
    }
    if (newValue.indexOf('.') < 0 && newValue != '') {
        newValue = parseFloat(newValue);
    }
    return newValue;
};

3. 检查数字输入

export const utilCheckNumber = (e: any): number => {
    let newValue = e;

    newValue = newValue.replace(/\D/g, ''); //清除“数字”以外的字符
    /*整数不能大于14位*/
    if (newValue.length > 14) {
        newValue = '99999999999999';
    }
    return newValue;
};

4. 解决两个数相加精度丢失问题

/**
 * 解决两个数相加精度丢失问题
 * @param {number} a 加数1
 * @param {number} b 加数2
 * @returns {number} 相加结果
 */
export const utilFloatAdd = (a, b) => {
    if (isNaN(a) || isNaN(b)) {
        return 0;
    }

    const aDecimal = a.toString().split('.')[1] || '';
    const bDecimal = b.toString().split('.')[1] || '';
    const decimalLength = Math.max(aDecimal.length, bDecimal.length);
    const multiplier = Math.pow(10, decimalLength);
    return (utilFloatMul(a, multiplier) + utilFloatMul(b, multiplier)) / multiplier;
};

5. 解决两个数相减精度丢失问题

/**
 * 解决两个数相减精度丢失问题
 * @param a
 * @param b
 * @returns {Number}
 */
export const utilFloatSub = (a, b) => {
	return utilFloatAdd(a, -b);
};

6. 解决两个浮点数相乘精度丢失问题

/**
 * 解决两个浮点数相乘精度丢失问题
 * @param {number} a 浮点数1
 * @param {number} b 浮点数2
 * @returns {number} 相乘结果
 */
export const utilFloatMul = (a, b) => {
    if (typeof a !== 'number' || typeof b !== 'number' || isNaN(a) || isNaN(b)) {
        throw new TypeError('参数必须是数字类型');
    }

    const aString = a.toString();
    const bString = b.toString();
    const aDecimal = aString.split('.')[1] || '';
    const bDecimal = bString.split('.')[1] || '';
    const decimalLength = aDecimal.length + bDecimal.length;
    const aInt = parseInt(aString.replace('.', ''));
    const bInt = parseInt(bString.replace('.', ''));
    return (aInt * bInt) / Math.pow(10, decimalLength);
};

7. 解决两个数相除精度丢失问题

/**
 * 解决两个数相除精度丢失问题
 * @param {Number} a - 被除数
 * @param {Number} b - 除数
 * @returns {Number} - 返回 a/b 的结果
 */
export const utilFloatDivide = (a, b) => {
    if (typeof a !== 'number' || typeof b !== 'number') {
        throw new Error('参数必须是数字类型');
    }
    if (b === 0) {
        throw new Error('除数不能为0');
    }

    let e = 0,
        f = 0;
    try {
        e = a.toString().split('.')[1].length;
    } catch (g) {}
    try {
        f = b.toString().split('.')[1].length;
    } catch (g) {}

    const c = Number(a.toString().replace('.', ''));
    const d = Number(b.toString().replace('.', ''));

    return utilFloatMul(c / d, Math.pow(10, f - e));
};

8. 分割小数点

/**
 * 分割小数点
 * @param {*} num
 * @returns
 */
export const numToQfw = num => {
    let arr = num.split('.');
    let str = arr[0];
    let reg = /(\d{1,3})(?=((\d{3}))+(\.\d*)?$)/g;
    str = str.replace(reg, '$&,');
    return `${str}.${arr[1]}`;
};

9. 4舍5入保留n位小数, 是否千分位展示

/**
 * 4舍5入保留n位小数
 * @param {*} num 数值
 * @param {*} digits 小数点后位数
 * @param {*} isFormatQfw 是否千分位展示(即:10000.105=>10,000.105;需要的话自行开启)
 * @returns
 */
export const utilRound = (num, digits = 0, isFormatQfw = false) => {
    if (typeof num === 'string') {
        num = Number(num);
    }
    let result = parseFloat(num);
    if (isNaN(result)) {
        return '';
    }
    result = Math.round(num * Math.pow(10, digits)) / Math.pow(10, digits);
    var s_x = result.toString();
    var pos_decimal = s_x.indexOf('.');
    if (pos_decimal < 0) {
        pos_decimal = s_x.length;
        s_x += '.';
    }
    while (s_x.length <= pos_decimal + digits) {
        s_x += '0';
    }
    return isFormatQfw ? numToQfw(s_x) : s_x;
};

10. 格式化金额

export const utilFormatAmount = (num: string | number): string => {
    if (!num) {
        return '0.00';
    }
    return !(num + '').includes('.')
        ? (num + '').replace(/\d{1,3}(?=(\d{3})+$)/g, match => {
                return match + ',';
          })
        : (num + '').replace(/\d{1,3}(?=(\d{3})+(\.))/g, match => {
                return match + ',';
          });
};

11. 金额每隔3位用逗号隔开,小数位不算

// 每隔3位用逗号隔开,小数位不算
export const utilAddCommas = number => {
    var result = '';
    if (!number) return result;
    // 将数字转换为字符串
    number = number.toString();

    // 检查是否含有小数部分
    var hasDecimal = false;
    if (number.indexOf('.') !== -1) {
        hasDecimal = true;
    }

    // 将整数部分每隔三位加上逗号
    var integerPart = '';
    if (hasDecimal) {
        integerPart = number.split('.')[0];
    } else {
        integerPart = number;
    }

    for (var i = integerPart.length - 1, count = 0; i >= 0; i--, count++) {
        if (count && count % 3 === 0) {
            result = ',' + result;
        }
        result = integerPart[i] + result;
    }

    // 如果有小数部分,则将小数部分加到结果中
    if (hasDecimal) {
        var decimalPart = number.split('.')[1];
        result += '.' + decimalPart;
    }

    return result;
};

12. 格式化表单搜索关键字

export const utilFormatKeyword = (str: string): string => {
    let newKeyword: string = str;
    newKeyword = newKeyword.trim();
    newKeyword = newKeyword.replace(/\s*[,,]\s*/g, ',');
    return newKeyword;
};

13. 设置高亮词

export const utilSetHeightLight = (keyword: string) => {
    let replaceString = `<span class="height-light-text">${keyword}</span>`;
    let reg;
    if (keyword != '') {
        reg = new RegExp(keyword, 'g');
    }
    const replaceHeightLight = (str): string => {
        let newStr = str;
        if (str && reg) {
            newStr = str.replace(reg, replaceString);
        }
        return newStr;
    };
    return {
        replaceHeightLight,
    };
};

14. 根据枚举值获取数组标签

export const utilGetArrLabelByValue = (arr: any = [], value) => {
    if (!Array.isArray(arr)) return;
    if (value === null || value === undefined) return;
    let result: any = {};
    result = arr.find(item => {
        return item.value.toString() === value.toString();
    });
    if (result?.label) return result.label;
    return '';
};

15. 时间戳转换成时间

export const utilTimestampToTime = timestamp => {
    if (!timestamp) return null;
    var date = new Date(timestamp * 1000); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() + ' ';
    var h = date.getHours() + ':';
    var m = date.getMinutes() + ':';
    var s = date.getSeconds();
    return Y + M + D + h + m + s;
};

16. 根据url下载文件

/**
 * 根据url下载文件(更改文件名)
 * @param {String} filePath - 文件路径 带http的完成路径
 * @param {String} fileName - 文件名
 * */
export const utilDownFileChangeName = (filePath = '', fileName = '') => {
    if (filePath?.indexOf('https') == -1) {
        filePath = AliyuncsCom + filePath;
    }
    const xhr = new XMLHttpRequest();
    xhr.open('GET', filePath, true);
    xhr.responseType = 'blob';
    xhr.onload = () => {
        if (xhr.status === 200) {
            var link = document.createElement('a');
            var body: any = document.querySelector('body');
            link.href = window.URL.createObjectURL(xhr.response);
            link.download = fileName;
            // fix Firefox
            link.style.display = 'none';
            body.appendChild(link);
            link.click();
            body.removeChild(link);
            window.URL.revokeObjectURL(link.href);
        }
    };
    xhr.send();
};

17. 获取URL中指定查询参数的值

/**
 * 获取URL中指定查询参数的值(专门用在vue页面嵌在iframe时的取值)
 * @param key 查询参数的名称
 * @param isParent 是否在父级窗口的URL中查找,默认为true
 * @returns 若查找到则返回查询参数的值,未查找到返回null
 */
export const utilUrlFind = (key: string, isParent: boolean = true): string | null => {
    const reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)', 'i');
    let r = <any>[];
    if (isParent) {
        r = window.parent.document.location.search.slice(1).match(reg);
    } else {
        r = window.location.search.slice(1).match(reg);
    }
    if (r != null) return decodeURI(r[2]);
    return null;
};

18. 对象转成查询参数

/** 
    对象转成查询参数
    实例:{a:1,b:2}=> a=1&b=2 
*/
export const utilObjToParam = (obj: any = {}) => {
    var ary = <any>[];
    for (var p in obj)
        if (obj.hasOwnProperty(p) && obj[p]) {
            ary.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
        }
    return ary.join('&');
};

19. 阿拉伯数字转换成大写

export const utilConvertToChinese = n => {
    if (n === 0) return '零';
    if (!n) return '';
    if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n)) {
        return '数据非法'; //判断数据是否大于0
    }
    let unit = '千百拾亿千百拾万千百拾元角分',
    str = '';
    n += '00';
    let indexpoint = n.indexOf('.'); // 如果是小数,截取小数点前面的位数
    if (indexpoint >= 0) {
        n = n.substring(0, indexpoint) + n.substr(indexpoint + 1, 2); // 若为小数,截取需要使用的unit单位
    }
    unit = unit.substring(unit.length - n.length); // 若为整数,截取需要使用的unit单位
    for (let i = 0; i < n.length; i++) {
        str += '零壹贰叁肆伍陆柒捌玖'.charAt(n.charAt(i)) + unit.charAt(i); //遍历转化为大写的数字
    }

    return str
        .replace(/零(千|百|拾|角)/g, '零')
        .replace(/(零)+/g, '零')
        .replace(/零(万|亿|元)/g, '$1')
        .replace(/(亿)万|壹(拾)/g, '$1$2')
        .replace(/^元零?|零分/g, '')
        .replace(/元$/g, '元整'); // 替换掉数字里面的零字符,得到结果
};

20. 根据url下载阿里云视频文件

/**
 * 根据url下载阿里云视频文件
 * @param {String} filePath - 文件路径 带http的完成路径
 * @param {String} fileName - 文件名
 */
export const utilDownloadVideo = async (filePath, fileName) => {
    let href = filePath;
    let response = await fetch(href);
    let blob = await response.blob();
    let objectUrl = window.URL.createObjectURL(blob);
    let a = document.createElement('a');
    a.href = objectUrl;
    a.download = fileName;
    a.click();
    a.remove();
};

21. 判断对应数据是否为空

/**
 * 判断对应数据是否为空
 * @param {Object} object - 对象
 */
export const utilObjValueAllEmpty = object => {
    var isEmpty = true;
    Object.keys(object).forEach(function (x) {
        if (object[x] != null && object[x] != '') {
            isEmpty = false;
        }
    });
    return isEmpty;
};

22. 划线命名转换为驼峰命名

// 下划线命名转换为驼峰命名
export const utilToCamelCase = str => {
    return str.replace(/_([a-z])/g, function (match, char) {
        return char.toUpperCase();
    });
};

23. 驼峰命名转下划线命名

// 驼峰命名转下划线命名
export const utilToUnderscore = str => {
    return str.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase();
};