项目中用到的一些方法(持续更新2024-10-15)

110 阅读4分钟
  • 处理树形结构中children为空的项
export function deleteChildren(arr: any) {
  let child = arr;
  for (let i = child.length; i--; i > 0) {
    if (child[i].children) {
      if (child[i].children.length) {
        deleteChildren(child[i].children);
      } else {
        delete child[i].children;
      }
    }
  }
  return arr;
}
  • 树形结构数据,根据id值获取对应的节点
/**
 * @description: 树形结构数据,通过ID值获取对应的地名节点
 * @param {树型结构数据} tree
 * @param {id值} id
 * @return {*}
 */
export function getLocationName(tree: any, id: any) {
  var isGet = false;
  var retNode = null;
  function deepSearch(tree: any, id: any) {
    for (var i = 0; i < tree.length; i++) {
      if (tree[i].children && tree[i].children.length > 0) {
        deepSearch(tree[i].children, id);
      }
      if (id === tree[i].locationId || isGet) {
        isGet || (retNode = tree[i]);
        isGet = true;
        break;
      }
    }
  }
  deepSearch(tree, id);
  return retNode;
}
  • 通过子节点的id值找父级节点的id值
/**
* @description: 通过cityId找父级省份id
* @return {*}
*/
//data:要遍历的数据, target:查找的子节点id值, result用于装查找结果的数组
export const findParent = (data:any, target:any, result:any) => {
 for (let i in data) {
   let item = data[i]
   if (item.locationId === target) {
     //将查找到的目标数据加入结果数组中
     //可根据需求unshift(item.id)或unshift(item)
     result.unshift(item.locationId)
     return true
   }
   if (item.children && item.children.length > 0) {
     let ok = findParent(item.children, target, result)
     if (ok) {
       result.unshift(item.locationId)
       return result
     }
   }
 }
 //走到这说明没找到目标
 return false
}
  • 属性名下划线转驼峰
/**
 * @description: 属性名下划线转驼峰
 * @param {any} data
 * @return {*}
 */
export function toCamel(data: any) {
  if (typeof data != 'object' || !data) return data;
  if (Array.isArray(data)) {
    return data.map((item: any) => toCamel(item));
  }

  const newData: any = {};
  for (let key in data) {
    let newKey = key.replace(/_([a-z])/g, (p, m) => m.toUpperCase());
    newData[newKey] = toCamel(data[key]);
  }
  return newData;
}
  • 根据label找对应value
export function valueFind(valueList: any, key: any) {
  return valueList.value.find((item: any) => item.label === key).value;
}
  • 根据value找对应label值
export function labelFind(valueList: any, val: any) {
  return valueList.find((item: any) => item.value == val).label;
}
  • 根据出生年月计算年龄
/**
 * @description: 根据出生年月计算年龄
 * @param {*} val
 * @return {*}
 */
export function getAge(val: any) {
  let currentYear = new Date().getFullYear(); //当前的年份
  let calculationYear = new Date(val).getFullYear(); //计算的年份
  const wholeTime = currentYear + val.substring(4); //周岁时间
  const calculationAge = currentYear - calculationYear; //按照年份计算的年龄
  //判断是否过了生日
  if (new Date().getTime() > new Date(wholeTime).getTime()) {
    return calculationAge;
  } else {
    return calculationAge - 1;
  }
}
  • 转换日期格式为'yyyy-MM-dd HH:mm:ss'
export function formatDate (oldDate) {
  function add0 (num) { return num < 10 ? '0' + num : num };// 个位数的值在前面补0
  const date = new Date(oldDate);
  const Y = date.getFullYear();
  const M = date.getMonth() + 1;
  const D = date.getDate();
  const h = date.getHours();
  const m = date.getMinutes();
  const s = date.getSeconds();

  const dateString = Y + '-' + add0(M) + '-' + add0(D) + ' ' + add0(h) + ':' + add0(m) + ':' + add0(s);
  return dateString;
}
  • 数字转金额
export function parseMoney(num) {
  if (!num) {
    return "0.00";
  }
  num = Math.round(num * 100) / 100;
  let result = num.toLocaleString();

  // 小数位补零
  var arrayNum = result.split(".");
  if (arrayNum.length === 1) {
    result += ".00";
  }
  if (arrayNum.length === 2) {
    if (arrayNum[1].length < 2) {
      result += "0";
    }
  }
  return result;
}
  • 获取当前时间(年,月,日)
export function getDateTime (type : string) {
    let date = new Date();
    let hengGang = "-";
    let maoHao = ":";
    let year : any = date.getFullYear();
    let month : any = date.getMonth() + 1;
    let curDate : any = date.getDate();
    let curHours : any = date.getHours();
    let curMinutes : any = date.getMinutes();
    let curSeconds : any = date.getSeconds();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (curDate >= 0 && curDate <= 9) {
        curDate = "0" + curDate;
      }
      if (curHours >= 0 && curHours <= 9) {
        curHours = "0" + curHours;
      }
      if (curMinutes >= 0 && curMinutes <= 9) {
        curMinutes = "0" + curMinutes;
      }
      if (curSeconds >= 0 && curSeconds <= 9) {
        curSeconds = "0" + curSeconds;
      }
      let currentDate = "";
      if (type == "year") {
        currentDate = year;
        return currentDate;
      } else if (type == "month") {
        currentDate = year + hengGang + month;
        return currentDate;
      } 
      else if(type == 'currentMonth'){
        return month;
      }
      else {
        currentDate = year + hengGang + month + hengGang + curDate + " " + curHours + maoHao + curMinutes + maoHao + curSeconds;
        return currentDate;
      }
    }
  • 获取当前时间 YYYT-MM
const getCurrentDate = () => {
  const date = new Date();
  const year: any = date.getFullYear();
  let month: any = date.getMonth() + 1;
  // 对月份进行处理,1-9月在前面添加一个“0”
  if (month >= 1 && month <= 9) {
    month = '0' + month;
  }
  const currentDate = year + '-' + month;
  return currentDate;
};
  • 获取当前月份的上一个月
/**
 *
 * @param currentDate 当前日期 格式YYYY-MM
 * @returns 当前日期的上一个月 格式YYYY-MM (注:1月的上一个月是上一年12月)
 */

export const getUpMonth = (currentDate: any) => {
  const year = currentDate.split('-')[0]; //获取当前日期的年
  const month = currentDate.split('-')[1]; //获取当前日期的月

  let year2 = year;
  let month2: any = parseInt(month) - 1;
  if (month2 == 0) {
    year2 = parseInt(year2) - 1;
    month2 = 12;
  }
  if (month2 < 10) {
    month2 = '0' + month2;
  }
  const m = year2.toString();
  const n = month2.toString();
  const t2 = m + '-' + n;
  return t2;
};
  • 检查浏览器是否开启了书签栏
export const bookmarksBarVisible = () =>{

    let isBookmarksBarVisible = false;
    
    if (window.innerHeight > 0) {
      // 检查窗口高度是否发生变化
      let prevHeight = window.innerHeight;
      window.addEventListener('resize', function() {
        if (window.innerHeight < prevHeight) {
          // 窗口高度变小,说明书签栏被开启
          isBookmarksBarVisible = true;
          console.log('书签栏是否可见:', isBookmarksBarVisible);
        } else {
          // 窗口高度变大,说明书签栏被关闭
          isBookmarksBarVisible = false;
          console.log('书签栏是否可见:', isBookmarksBarVisible);
        }
        prevHeight = window.innerHeight;
      });
    }
    return isBookmarksBarVisible;
}
  • 获取浏览器书签栏的高度
export const getBookmarksBarHeight = () => {

    let bookmarksBarHeight = 0;
    
    if (window.innerHeight > 0) {
      // 创建一个隐藏的 div 元素并添加到 body 中
      let div = document.createElement('div');
      div.style.position = 'fixed';
      div.style.top = '-1000px';
      div.style.left = '-1000px';
      div.style.width = '100px';
      div.style.height = '100px';
      div.style.overflow = 'scroll';
      document.body.appendChild(div);
    
      // 等待 div 元素渲染完成后获取书签栏高度
      setTimeout(function() {
        bookmarksBarHeight = div.offsetHeight - div.clientHeight;
        console.log('书签栏高度为:', bookmarksBarHeight);
        document.body.removeChild(div);
      }, 10);
    }
}
  • 防抖函数
/**防抖 */
export function debounce(func, wait) {
  let timeout;
  return function() {
      const context = this;
      const args = arguments;
      clearTimeout(timeout);
      timeout = setTimeout(function() {
          func.apply(context, args);
      }, wait);
  };
}

使用:
data() {
     return {
        //....
        // 防抖函数
        debouncedHandleInput: null,
       }
    },
// 在组件创建时初始化防抖函数
this.debouncedHandleInput = debounce(this.handleInput.bind(this), 300);
//在组件中应用防抖函数
<u--input @change="debouncedHandleInput($event,month)" border="none" :value="formData[month.monthId]" placeholder="请输入" ></u--input>