当前位置:首页 > elementui > 正文内容

公用方法

自由小鸟2年前 (2022-09-16)elementui774

1,deepClone 深度拷贝方法
2,deepMerge 合并对象
3,oninput 金额只能是数字保留2位小数
<el-input
@keyup.native=”
ruleForm.totalAmount = oninput(ruleForm.totalAmount, 2)

:disabled=”NoChange”
v-model=”ruleForm.totalAmount”
maxlength=”50”
placeholder=”请输入阿拉伯数字或小数”
class=”newWidth”
@blur=”totalMoneyFn(ruleForm.totalAmount, ruleForm)”
></el-input>
4,rbstateFormat 价格千位符
<el-table-column :formatter="rbstateFormat" prop="totalAmount" width="96px" align="right" label="申请金额(元)" >
</el-table-column>


function judgeType(obj) {
  const toString = Object.prototype.toString;
  const map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object',
  };
  if (obj instanceof Element) {
    return 'element';
  }
  return map[toString.call(obj)];
}
export function deepClone(data) {
  const type = judgeType(data);
  let obj;
  if (type === 'array') {
    obj = [];
  } else if (type === 'object') {
    obj = {};
  } else {
    // 不再具有下一层次
    return data;
  }
  if (type === 'array') {
    for (let i = 0, len = data.length; i < len; i++) {
      obj.push(deepClone(data[i]));
    }
  } else if (type === 'object') {
    // 对原型上的方法也拷贝了....
    for (const key in data) {
      obj[key] = deepClone(data[key]);
    }
  }
  return obj;
}

export function deepMerge(obj1, obj2) {
  let key
  for (key in obj2) {
    obj1[key] =
      obj1[key] &&
        obj1[key].toString() === '[object Object]' &&
        (obj2[key] && obj2[key].toString() === '[object Object]')
        ? deepMerge(obj1[key], obj2[key])
        : (obj1[key] = obj2[key])
  }
  return obj1
}


export function oninput(val, limit = 0) {
  val = val.replace(/[^\d.]/g, ""); //保留数字
  val = val.replace(/^00/, "0."); //开头不能有两个0
  val = val.replace(/^\./g, "0."); //开头为小数点转换为0.
  val = val.replace(/\.{2,}/g, "."); //两个以上的小数点转换成一个
  val = val.replace(".", "$#$").replace(/\./g, "").replace("$#$", "."); //只保留一个小数点
  /^0\d+/.test(val) ? (val = val.slice(1)) : ""; //两位以上数字开头不能为0
  const str = "^(\\d+)\\.(\\d{" + limit + "}).*$";
  const reg = new RegExp(str);
  if (limit === 0) {
    // 不需要小数点
    val = val.replace(reg, "$1");
  } else {
    // 通过正则保留小数点后指定的位数
    val = val.replace(reg, "$1.$2");
  }
  if (val.length <= 18) {
    return val;
  } else {
    return val.slice(0, 18)
  }
}

export function strlen(str) {
  var len = 0;
  for (var i = 0; i < str.length; i++) {
    var c = str.charCodeAt(i);
    //单字节加1
    if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
      len++;
    } else {
      len += 2;
    }
  }
  return len;
}

export function get_cut_str(str, length) {
  var a = str.match(/[^\x00-\xff]|\w{1,2}/g);
  return a.length < length ? str : a.slice(0, length).join("") + "...";
}

export function rbstateFormat(row, column, cellValue) {
  if (cellValue !== null) {
    cellValue = Number(cellValue).toFixed(2)
    cellValue += '';
    if (!cellValue.includes('.')) cellValue += '.';
    return cellValue.replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
      return $1 + ',';
    }).replace(/\.$/, '');
  }
}

export function geturl() {
  let geturl = window.location.href;
  if (geturl.indexOf("apply") != -1) {
    return true;
  } else {
    return false;
  }
}


/* eslint-disable */
let data = {}
// 通用工具类
export default class CommonUtils {
  /**
   * 文件预览
   * @param blob 二进制文件流
   * @param fileName 文件名称(包含文件拓展名)
   */
  static openPreview(blob, fileName) {
    var preview = false // 是否预览
    var option = null // Blob 下载文件时 type
    if(fileName.endsWith('pdf')) {
      option = {
        type: 'application/pdf;charset=utf-8'
      }
      preview = true
    } else if (fileName.endsWith('gif')) {
      option = {
        type: 'image/gif'
      }
      preview = true
    } else if (fileName.endsWith('jpeg') || fileName.endsWith('jpg') || fileName.endsWith('jfif')) {
      option = {
        type: 'image/jpeg'
      }
      preview = true
    } else if (fileName.endsWith('png')) {
      option = {
        type: 'image/png'
      }
      preview = true
    } else if (fileName.endsWith('doc')) {
      option = {
        type: 'application/msword;charset=utf-8'
      }
    } else if (fileName.endsWith('docx')) {
      option = {
        type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'
      }
    } else if (fileName.endsWith('ppt')) {
      option = {
        type: 'application/vnd.ms-powerpoint;charset=utf-8'
      }
    } else if (fileName.endsWith('pptx')) {
      option = {
        type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation;charset=utf-8'
      }
    } else if (fileName.endsWith('txt')) {
      option = {
        type: 'text/plain;charset=utf-8'
      }
      preview = true
    } else if (fileName.endsWith('xls')) {
      option = {
        type: 'application/vnd.ms-excel;charset=utf-8'
      }
    } else if (fileName.endsWith('xlsx')) {
      option = {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
      }
    } else if (fileName.endsWith('zip')) {
      option = {
        type: 'application/zip'
      }
    } else if (fileName.endsWith('rar')) {
      option = {
        type: 'application/x-rar-compressed'
      }
    }
    let fileBlob = new Blob([blob], option)
    if(preview) {
      var src = window.URL.createObjectURL(fileBlob)
      window.open(src)
      // window.URL.revokeObjectURL(src);
    } else {
      var link = document.createElement('a')
      var body = document.querySelector('body')
      link.href =  window.URL.createObjectURL(fileBlob)
      link.download = fileName
      link.style.display = 'none'
      body.appendChild(link)
      link.click();
      body.removeChild(link);
      window.URL.revokeObjectURL(link.href)
    }
  }

  /**
   * 获取当前时间的上一个月份
   * @returns {string}  'yyyyMM'格式
   */
  static getPreMonth () {
    let dateValue = new Date()
    let year = dateValue.getFullYear()
    let month = dateValue.getMonth()
    if (month === 0) {
      year = parseInt(year) - 1
      month = 12
    }
    return year + (month > 9 ? '' + month : '0' + month)
  }
  // 获取当前月
  static getCurrentMonth () {
    let dateValue = new Date()
    let year = dateValue.getFullYear()
    let month = dateValue.getMonth() + 1
    if (month === 0) {
      year = parseInt(year) - 1
      month = 12
    }
    return year + '-' +(month > 9 ? '' + month : '0' + month)
  }
  /**
   * 获取全部数据
   */
  static getData () {
    return data
  }
  /**
   * 保存一个数据值
   * @param key
   * @param dataItem
   */
  static setItem (key, dataItem) {
    data[key] = dataItem
  }

  /**
   * 获取一个数据值
   * @param key
   * @returns {*}
   */
  static getItem (key) {
    return data[key]
  }
  /**
   * 时间CST格式转化为GMT格式
   * @param strDate 当前要转化的CST格式
   * @returns {time} 转化为GMT格式
   */
  static dateToGMT (strDate) {
    let dateStr = strDate.split(' ')
    let strGMT = dateStr[0] + ' ' + dateStr[1] + ' ' + dateStr[2] + ' ' + dateStr[5] + ' ' + dateStr[3] + ' GMT+0800'
    let date = new Date(Date.parse(strGMT))
    return date
  }
  /**
   * 转化日期时间
   * @param date 当前要转化的日期
   * @returns {string} 转化为的日期格式‘xxxx年xx月’
   */
  static formatMonthCN (date) {
    let dateValue = new Date(date)
    return dateValue.getFullYear() + '年' + (parseInt(dateValue.getMonth() + 1) > 9 ? parseInt(dateValue.getMonth() + 1) : '0' + parseInt(dateValue.getMonth() + 1)) + '月'
  }

  /**
   * 转化日期时间
   * @param date 当前要转化的日期
   * @returns {string} 转化为的日期格式‘xxxx年xx月xx日’
   */
  static formatDateCN(date) {
    let dateValue = new Date(date)
    return dateValue.getFullYear() + '年' + (parseInt(dateValue.getMonth() + 1) > 9 ? parseInt(dateValue.getMonth() + 1) : '0' + parseInt(dateValue.getMonth() + 1)) + '月' + (dateValue.getDate() > 9 ? dateValue.getDate() : '0' + dateValue.getDate()) + '日 '
  }

  /**
   * 转化日期
   * @param date 当前要转化的日期
   * @returns {string} 转化为的日期格式‘xxxx/xx/xx’
   */
  static formatTableDate(date) {
    let dateValue = new Date(date)
    return '' + dateValue.getFullYear() + '/' + (parseInt(dateValue.getMonth() + 1) > 9 ? parseInt(dateValue.getMonth() + 1) : '0' + parseInt(dateValue.getMonth() + 1)) + '/' + (dateValue.getDate() > 9 ? dateValue.getDate() : '0' + dateValue.getDate())
  }

  /**
   * 转化日期
   * @param date 当前要转化的日期
   * @returns {string} 转化为的日期格式‘xxxx-xx’
   */
  static formateMonth(date) {
    let dateValue = new Date(date)
    return '' + dateValue.getFullYear() + '-' + (parseInt(dateValue.getMonth() + 1) > 9 ? parseInt(dateValue.getMonth() + 1) : '0' + parseInt(dateValue.getMonth() + 1))
  }

  /**
   * 转化日期
   * @param date 当前要转化的日期
   * @returns {string} 转化为的日期格式‘xxxx-xx-xx’
   */
  static formatDate(date) {
    let dateValue = new Date(date)
    return '' + dateValue.getFullYear() + '-' + (parseInt(dateValue.getMonth() + 1) > 9 ? parseInt(dateValue.getMonth() + 1) : '0' + parseInt(dateValue.getMonth() + 1)) + '-' + (dateValue.getDate() > 9 ? dateValue.getDate() : '0' + dateValue.getDate())
  }

  /**
   * 转化日期时间
   * @param date 当前要转化的日期
   * @returns {string} 转化为的日期格式‘xxxx年xx月xx日 xx:xx’
   */
  static formatDateTime (date) {
    let dateValue = new Date(date)
    return dateValue.getFullYear() + '年' + (parseInt(dateValue.getMonth() + 1) > 9 ? parseInt(dateValue.getMonth() + 1) : '0' + parseInt(dateValue.getMonth() + 1)) + '月' + (dateValue.getDate() > 9 ? dateValue.getDate() : '0' + dateValue.getDate()) + '日 ' + '' + (dateValue.getHours() > 9 ? dateValue.getHours() : '0' + dateValue.getHours()) + ':' + (dateValue.getMinutes() > 9 ? dateValue.getMinutes() : '0' + dateValue.getMinutes())
  }
  /**
   * 转化日期时间
   * @param date 当前要转化的日期20200826121152
   * @returns {string} 转化为的日期格式‘xxxx-xx-xx- xx:xx’
   */
  static formatSetTime (date) {
    let dataStr = date ? date.substr(0, 4) + '-' + date.substr(4, 2) + '-' + date.substr(6, 2) + ' ' + date.substr(8, 2) + ':' + date.substr(10, 2) + ':' + date.substr(12, 2) : date
    return dataStr
  }

  /**
   * 将时间转化为月份
   * @param date 当前要转化的日期
   * @returns {string} 转化为的日期格式‘yyyyMM’
   */
  static formatMonth (date) {
    let dateValue = new Date(date)
    return dateValue.getFullYear() + '-' + (parseInt(dateValue.getMonth() + 1) > 9 ? parseInt(dateValue.getMonth() + 1) : '0' + parseInt(dateValue.getMonth() + 1))
  }
  /**
   * 将时间转化为月份
   * @param date 当前要转化的日期2020-05
   * @returns {string} 转化为的日期格式‘yyyyMM202005’
   */
  static formatNumb (date) {
    let dataStr = date ? date.substr(0, 4) + date.substr(5, 2) : date
    return dataStr
  }
  /**
   * 将时间转化为月份
   * @param date 当前要转化的日期yyyy-MM-dd
   * @returns {string} 转化为的日期格式‘yyyyMMdd’
   */
  static formatNumdate (date) {
    let dataStr = date ? date.substr(0, 4) + date.substr(5, 2) + date.substr(8, 2) : date
    return dataStr
  }
  /**
   * 将时间转化为yyyy-MM-dd
   * @param date 当前要转化的日期
   * @returns {yyyyMMdd} 字符串转化为的日期格式‘yyyy-MM-dd’
   */
  static formatStr (date) {
    let dataStr = date ? date.substr(0, 4) + '-' + date.substr(4, 2) + '-' + date.substr(6, 2) : date
    return dataStr
  }

  /**
   * 将时间转化为yyyy-MM-dd
   * @param date 当前要转化的日期
   * @returns {yyyyMMdd} 字符串转化为的日期格式‘yyyy-MM-dd’
   */
  static formatStrTime (date) {
    let dataStr = date ? date.substr(8, 2) + ':' + date.substr(10, 2) + ':' + date.substr(12, 2) : date
    return dataStr
  }

  /**
   * 检查返回结果
   * @param res 后台返回数据
   * @returns {boolean}
   */
  static checkResultData (res) {
    if (res.code === 0 || res.message === 'Success') {
      return true
    }
    return false
  }
  /**
   * 深度拷贝数据
   * @param source 元数据
   * @param ignoreNull 是否拷贝集合
   * @returns 拷贝后的集合
   */
  static deepClone (source, ignoreNull) {
    if (!source || typeof source !== 'object') {
      throw new Error('error arguments', 'shallowClone')
    }
    if (ignoreNull == null) {
      ignoreNull = false
    }
    let targetObj = source.constructor === Array ? [] : {}
    for (let keys in source) {
      if (source.hasOwnProperty(keys)) {
        if (source[keys] && typeof source[keys] === 'object') {
          targetObj[keys] = source[keys].constructor === Array ? [] : {}
          targetObj[keys] = this.deepClone(source[keys])
        } else {
          if (ignoreNull) {
            if (source[keys] != null && source[keys] !== '') {
              targetObj[keys] = source[keys]
            }
          } else {
            targetObj[keys] = source[keys]
          }
        }
      }
    }
    return targetObj
  }
  /**
   * 合并对象
   */
  static mergeObject (options, def) {
    for (let key in def) {
      if (options[key] === undefined) {
        options[key] = def[key]
      }
    }
    return options
  }
  /**
   * 组装删除数据
   * @param arrayObj 删除对象数据
   * @param attribute 取值Name(默认id)
   * @returns 组装后的删除数据
   */
  static objectToDeleteIds (objs, idName) {
    let deleteData = Object()
    deleteData.primarykey = null
    deleteData.ids = []
    idName = idName === null || idName === 'undefined' ? 'id' : idName
    for (let i = 0; i < objs.length; i++) {
      deleteData.ids[i] = objs[i][idName]
    }
    deleteData = deleteData.ids
    return deleteData
  }
  /**
   * 组装查询数据
   * @param obj 查询对象
   * @returns {string}
   */
  static objectToQueryData (obj) {
    for(let key in obj){
      obj[key] = obj[key] == '' ? null : obj[key]
    }
    return obj
  }
  /**
   * 初始化翻页数据
   * @param _this 当前vue对象
   * @param functionObj 每次页变动后回调方法
   */
  static init (_this, functionObj) {
    let __this = this
    _this.page = _this.page == null || _this.page == 0 ? this.deepClone(_this.$Config.page) : _this.page
    _this.loading = true
    _this.currentChange = function (page) {
      _this.page.currentPage = page
      _this.page.isSearch = false
      __this.execFunction(functionObj)
    }
    _this.sizeChange = function (size) {
      _this.page.isSearch = false
      _this.page.pageSize = size
      __this.execFunction(functionObj)
    }
    _this.indexMethod = function (index) {
      let curpage = _this.page.currentPage   //单前页码,具体看组件取值
      let limitpage = _this.page.pageSize    //每页条数,具体是组件取值
      return (index+1) + (curpage-1)*limitpage
      __this.execFunction(functionObj)
    }
    __this.execFunction(functionObj)
  }

  /**
   * 查询返回数据组装table数据
   * @param result 后端返回数据
   * @returns {*}
   */
  static resultToTableData (_this, res, dicts) {
    console.log(res.data, 'ssszd')
    if (res.data) {
      _this.page.total = res.data.totalElements
    }
    let items = res.data.data
    if (_this.enum_code) {
      let codes = _this.enum_code.split(',')
      for (let l in items) {
        codes.forEach(value => {
          let code = value.split(':')
          if (code == null || code.length === 0) {
            return
          }
          let fk = code.length === 1 ? code[0] : code[1]
          let fv = items[l][fk]
          let dictList = dicts[code[0]] == null ? null : dicts[code[0]]
          if (dictList != null) {
            let dict = null
            for (let i in dictList) {
              if (i === fv) {
                dict = dictList[i]
                if (items[l]['children']) {
                  this.resultToTableData(_this, {data: {data: items[l]['children']}}, dicts)
                }
              }
            }
            items[l][fk + 'Name'] = dict != null ? dict : ''
          }
        })
      }
    }
    return items
  }
  /**
   * 数据检测(将原来的数据和修改过后的数据对比,取改动过的数据,id必取)
   * @param data 数据对象
   * @param oldData 原来的数据对象
   * @param idName id名称
   * @param versionName 版本名称
   * @returns {*}
   */
  static objectToUpdateData (data, oldData, idName, versionName) {
    if (data instanceof Array) {
      let result = []
      let old = {}
      oldData.forEach(v => {
        old[v[idName]] = v
      })
      let i = 0
      data.forEach(v => {
        let obj = this.objectToUpdate(v, old[v[idName]], idName, versionName)
        if (obj != null) {
          result[i] = obj
          i++
        }
      })
      if (result.length === 0) {
        return null
      }
      return result
    } else {
      return this.objectToUpdate(data, oldData, idName, versionName)
    }
  }
  /**
   * 数据检测(将原来的数据和修改过后的数据对比,取改动过的数据,id必取)
   * @param data 数据对象
   * @param oldData 原来的数据对象
   * @param idName id名称
   * @param versionName 版本名称
   * @returns {*}
   */
  static objectToUpdate (data, oldData, idName, versionName) {
    if (oldData == null) {
      return data
    }
    let i = 0
    let updateData = {}
    for (let key in data) {
      if (data[key] !== oldData[key]) {
        i++
        updateData[key] = data[key] ? data[key] : ''
      }
    }
    if (i === 0) {
      return null
    }
    if (idName == null) {
      idName = 'id'
      versionName = 'version'
    }
    updateData[idName] = data[idName]
    updateData[versionName] = data[versionName]
    return updateData
  }
  /**
   * 组装保存数据
   * @param formData 保存的对象
   * @returns {string}
   */
  static objectToInsertData (formData) {
    return formData
    // const insertData = {}
    // insertData.dicts = []
    // insertData.items = []
    // insertData.itemCount = 0
    // insertData.resultHint = null
    // insertData.parentID = null
    // if (formData instanceof Array) {
    //   insertData.items = formData
    // } else {
    //   insertData.items[0] = formData
    // }
    // return JSON.stringify(insertData)
  }
  /**
   * 字典数据集合转map
   * @param lists
   */
  static listToMapDict (lists) {
    let dictMap = {}
    for (let i in lists) {
      let values = lists[i]
      dictMap[lists[i].enumCode] = values.items
    }
    return dictMap
  }
  /**
   * 执行方法
   * @param functionObj 方法体
   */
  static execFunction (functionObj, data) {
    if (functionObj != null) {
      functionObj(data)
    }
  }
  /**
   * 执行方法
   * @param functionObj 方法体
   */
  static execCheckFunction (_this, formName, functionObj, data) {
    let check = _this.$refs[formName]
    if (check == null) {
      functionObj(data)
    } else {
      check.validate(function (valid) {
        if (valid) {
          functionObj(data)
        }
      })
    }
  }
  /**
   * 初始化高度
   * @param _this
   * @param btnHeight
   */
  static initStyleLayer (_this, btnHeight) {
    _this.mainStyle = {}
    if (btnHeight == null) {
      btnHeight = 50
    }
    _this.mainStyle.height = parseInt(_this.props.style.height) - parseInt(_this.props.style.title.height) - btnHeight + 15 + 'px'
    _this.mainStyle.padding = '10px 10px 10px 10px'
    _this.mainStyle.overflow = 'auto'

    _this.btnStyle = {}
    _this.btnStyle.paddingRight = '10px'
    _this.btnStyle.marginTop = '5px'
    // _this.btnStyle.height = btnHeight + 'px'
    _this.btnStyle.lineHeight = '40px'
    _this.btnStyle.textAlign = 'center'
    _this.btnStyle.borderTop = '1px solid #ccc'
  }

  /**
   * 根据list的name的值删除list
   * @param list
   * @param name
   * @param value
   */
  static deleteListObj (list, value, name) {
    if (name == null) {
      for (let i in list) {
        if (value === list[i]) {
          list.splice(i, 1)
          break
        }
      }
    } else {
      for (let i in list) {
        if (value === list[i][name]) {
          list.splice(i, 1)
          break
        }
      }
    }
    return list
  }

  /**
   * 通过list的name的值查询value的集合
   * @param list
   * @param name
   * @param value
   * @returns {*}
   */
  static findListObj (list, name, value) {
    let v = list.filter(v => {
      if (v[name] === value) {
        return v
      }
    })
    if (v == null || v.length === 0) {
      return []
    }
    return v
  }
  /**
   * 创建查询的this对象
   * @param _this
   */
  static createQuery (_this) {
    let queryThis = {}
    queryThis.$Config = _this.$commonUtil.deepClone(_this.$Config)
    queryThis.page = queryThis.$Config.page
    return queryThis
  }

  /**
   * 返回千分制字符串
   * @param num 数字
   * @returns {string}
   */
  static format (num) {
    let str = num + ''
    let re = /(\d{1,3})(?=(\d{3})+(?:$|\.))/g
    if (str.indexOf('.') > -1) {
      let array = str.split('.')
      return array[0].replace(re, '$1,') + '.' + array[1]
    } else {
      return str.replace(re, '$1,')
    }
  }
  static analyClassType (_this, data) {
    if (data == null || data.length === 0) {
      return new Promise(function (resolve, reject) {
        resolve([])
      })
    }
    return _this.$curdUtilV2.queryClassTree(_this).then(classData => {
      // 把分类解析成单分类
      let cd = {}
      if (classData == null || classData.length === 0) {
        return data
      }
      classData.forEach(v => {
        v.enumItemCode = v.enumCode
        v.enumItemName = v.enumName
      })
      classData.forEach(v => {
        this.classTypeOne(v, cd)
      })
      let codes = _this.tree_code == null ? [] : _this.tree_code.split(',')
      data.forEach(vv => {
        codes.forEach(code => {
          if (code != null) {
            let cod = code.split(':')
            let c = cod.length > 1 ? cod[1] : cod[0]
            let memberType = vv[c]
            if (memberType != null) {
              let classT = cd[vv[c]]
              if (classT != null) {
                vv[c + 'Name'] = classT['enumItemName']
              }
            }
          }
        })
      })
      return data
    })
  }
  static analyClassTypeList (_this, data) {
    if (data == null || data.length === 0) {
      return new Promise(function (resolve, reject) {
        resolve([])
      })
    }
    return _this.$curdUtilV2.queryClassTreeList(_this).then(classData => {
      // 把分类解析成单分类
      let cd = {}
      if (classData == null || classData.length === 0) {
        return data
      }
      classData.forEach(v => {
        v.enumItemCode = v.enumCode
        v.enumItemName = v.enumName
      })
      classData.forEach(v => {
        this.classTypeOne(v, cd)
      })
      let codes = _this.tree_code == null ? [] : _this.tree_code.split(',')
      data.forEach(vv => {
        codes.forEach(code => {
          if (code != null) {
            let cod = code.split(':')
            let c = cod.length > 1 ? cod[1] : cod[0]
            let memberType = vv[c]
            if (memberType != null) {
              let classT = cd[vv[c]]
              if (classT != null) {
                vv[c + 'Name'] = classT['enumItemName']
              }
            }
          }
        })
      })
      return data
    })
  }
  static classTypeOne (data, cd) {
    if (data instanceof Array) {
      data.forEach(v => {
        cd[v.enumItemCode] = v
        if (v.enumItemList != null && v.enumItemList.length !== 0) {
          this.classTypeOne(v.enumItemList, cd)
        }
      })
    } else {
      cd[data.enumItemCode] = data
      if (data.enumItemList != null && data.enumItemList.length !== 0) {
        this.classTypeOne(data.enumItemList, cd)
      }
    }
  }
  /**
   * 数字格式化
   * @param value
   * @returns {string|*}
   */
  static numFormat (value) {
    let tmp = value * 1
    if (isNaN(tmp)) {
      return value
    } else {
      return typeof value === 'string' ? value.replace(/(\d)(?=(\d{3})+\.)/g, '$1,') : JSON.stringify(value).replace(/(\d)(?=(\d{3})+\.)/g, '$1,')
    }
  }
  // 获得某月的天数
  static getMonthDays (myMonth) {
    let now = new Date() // 当前日期
    let nowYear = now.getFullYear() // 当前年
    var monthStartDate = new Date(nowYear, myMonth, 1)
    var monthEndDate = new Date(nowYear, myMonth + 1, 1)
    var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24)
    return days
  }
  // 获取当前月的第一天  20200701
  static getMonthStartDate () {
    let now = new Date() // 当前日期
    let nowMonth = now.getMonth() // 当前月
    let nowYear = now.getFullYear() // 当前年
    var monthStartDate = new Date(nowYear, nowMonth, 1)
    return this.formatDate(monthStartDate)
  }
  // 获取当前月的最后一天
  static getMonthEndDate () {
    let now = new Date() // 当前日期
    let nowMonth = now.getMonth() // 当前月
    let nowYear = now.getFullYear() // 当前年
    var monthEndDate = new Date(nowYear, nowMonth, this.getMonthDays(nowMonth))
    return this.formatDate(monthEndDate)
  }
  // 获取当前周的第一天
  static getWeekStartDate () {
    let now = new Date() // 当前日期
    let nowDayOfWeek = now.getDay() // 今天本周的第几天
    let nowDay = now.getDate() // 当前日
    let nowMonth = now.getMonth() // 当前月
    let nowYear = now.getFullYear() // 当前年
    var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1)
    return this.formatDate(weekStartDate)
  }
  // 获取当前周的最后一天
  static getWeekEndDate () {
    let now = new Date() // 当前日期
    let nowDayOfWeek = now.getDay() // 今天本周的第几天
    let nowDay = now.getDate() // 当前日
    let nowMonth = now.getMonth() // 当前月
    let nowYear = now.getFullYear() // 当前年
    var weekStartDate = new Date(nowYear, nowMonth, nowDay + (7 - nowDayOfWeek))
    return this.formatDate(weekStartDate)
  }
  // 为空检测
  static isEmpty(obj) {
    //检验null和undefined
    if (!obj && obj !== 0 && obj !== '') {
      return true;
    }
    //检验数组
    if (Array.prototype.isPrototypeOf(obj) && obj.length === 0) {
      return true;
    }
    //检验对象
    if (Object.prototype.isPrototypeOf(obj) && Object.keys(obj).length === 0) {
      return true;
    }
    return false;
  }
}
export function arrToObj(arr) {
  return arr.reduce(
    (obj, item) => ({ ...obj, [item.value]: item.label }),
    {}
  );
}

版权声明:本文由Web学习之路发布,如需转载请注明出处。

本文链接:https://webge.net/?id=150

“公用方法” 的相关文章

elementui -动态循环验证

<el-col :span="9"> <el-form-item label="消费总人数" :rules="[{required: true,pattern: /^(\d+)(.\d{0...

elementui 整个form禁止,但是除一些不禁止

在除外的外层添加一个el-form <el-form label-width="100px" :model="form" :disabled="true"> <el-form-item label="...

elmentui rules验证

totalAmount12: [ { required: true, message: "请输入借款金额", trigger: "blur" }, { pattern: /^(\d+)(.\d{1,50})?$/,...

上传组件 el-upload

<el-upload :on-success="uploadSuccess" :on-error="handleErr"...

el-table 里金额千分位符,保留两位小数

<el-table-column prop="amountRec" :formatter="rbstateFormat" label="金额" min-width="150" ></el-table-c...

elementui-plus 使用注意点

1,在使用图标注意点,如果使用动态图标需要全局注册图标,不然不会出现 import { createApp } from 'vue' import App from './App.vue' import router from './router'...