vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > vue时间类型转换

vue各种时间类型转换方法例子

作者:Mars空港

前端前后端接⼝处理时经常会遇到需要转换不同时间格式的情况,下面这篇文章主要给大家介绍了关于vue各种时间类型转换的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下

时间范围['2024-04-17 14:36:27', '2024-04-24 14:36:27']

console.log(this.$getRecentDays()); 页面使用默认7天  也可以指定console.log(this.$getRecentDays(30));

['2024-04-17 14:36:27', '2024-04-24 14:36:27']  默认值

function getDateString (date, fmt = 'yyyy-MM-dd') {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + '').substr(4 - RegExp.$1.length)
    )
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
  }
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + ''
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? str : padLeftZero(str)
      )
    }
  }
  return fmt
}
export function getRecentDays (duration = 7, fmt = 'yyyy-MM-dd hh:mm:ss') {
  let oneDayLong = 24 * 60 * 60 * 1000
  let nowTime = Date.now()
  let pre7DayTime = nowTime - duration * oneDayLong
  let now = new Date(nowTime)
  let pre7Day = new Date(pre7DayTime)
  return [getDateString(pre7Day, fmt), getDateString(now, fmt)]
}

开始时间结束时间['2024-04-17 00:00:00', '2024-04-24 23:59:59']

console.log(this.$todayTimer(30)); 也是可以自定义范围呢

export function todayTimer (duration = 7, fmt = 'yyyy-MM-dd') {
  let oneDayLong = 24 * 60 * 60 * 1000
  let nowTime = Date.now()
  let pre7DayTime = nowTime - duration * oneDayLong
  let now = new Date(nowTime)
  let pre7Day = new Date(pre7DayTime)
  return [
    getDateString(pre7Day, fmt) + ' ' + '00:00:00',
    getDateString(now, fmt) + ' ' + '23:59:59',
  ]
}

今年的起始时间 和结束时间 ['2024-01-01 00:00:00', '2024-12-31 23:59:59']

export function todayTimer (duration = 7, fmt = 'yyyy-MM-dd') {
  let oneDayLong = 24 * 60 * 60 * 1000
  let nowTime = Date.now()
  let pre7DayTime = nowTime - duration * oneDayLong
  let now = new Date(nowTime)
  let pre7Day = new Date(pre7DayTime)
  return [
    getDateString(pre7Day, fmt) + ' ' + '00:00:00',
    getDateString(now, fmt) + ' ' + '23:59:59',
  ]
}

当月的开始结束时间 ['2024-04-01 00:00:00', '2024-04-30 23:59:59']

export function ofMonth () {
  const startOfMonth = moment().startOf('month').format('YYYY-MM-DD 00:00:00'); // 本月的起始时间
  const endOfMonth = moment().endOf('month').format('YYYY-MM-DD 23:59:59'); // 本月的结束时间
  return [startOfMonth, endOfMonth]
}

最近几个月 ['2023-10-31 00:00:00', '2024-04-30 23:59:59']

最近几个月 ['2023-10-31 00:00:00', '2024-04-30 23:59:59']

 console.log(this.$recentMonths('month',6));

export function recentMonths (type, val) {
  const now = moment();
  if (type == 'day') {
    const startDate = now.clone().subtract(val - 1, 'days').startOf('day');
    const endDate = now.clone().endOf('day').hours(23).minutes(59).seconds(59);
    const dayRange = [startDate.format('YYYY-MM-DD HH:mm:ss'), endDate.format('YYYY-MM-DD HH:mm:ss')];
    return dayRange;
  }
  if (type == 'week') {
    const weeksAgo = now.clone().subtract(val - 1, 'weeks').startOf('isoWeek');
    const thisWeekEnd = now.clone().endOf('week').hours(23).minutes(59).seconds(59);
    const recentWeeksRange = [weeksAgo.format('YYYY-MM-DD HH:mm:ss'), thisWeekEnd.format('YYYY-MM-DD HH:mm:ss')];
    // console.log(recentWeeksRange);
    return recentWeeksRange;
  }
  if (type == 'month') {
    const sixMonthsAgo = now.clone().subtract(val, 'months').endOf('month').startOf('day');
    const thisMonthEnd = now.clone().endOf('month').hours(23).minutes(59).seconds(59);
    const recentSixMonthsRange = [
      sixMonthsAgo.format('YYYY-MM-DD HH:mm:ss'),
      thisMonthEnd.format('YYYY-MM-DD HH:mm:ss')
    ]
    return recentSixMonthsRange
  }
}

各种时间类型就不一一列了    

下面是完整的js代码

import * as moment from 'moment';
moment.suppressDeprecationWarnings = true;
// 封装的 一些关于时间的方法
function random (low, high) {
  if (arguments.length === 1) {
    high = low
    low = 0
  }
  return Math.floor(low + Math.random() * (high - low))
}

function randomOne (arr) {
  return arr[random(arr.length)]
}

function getDateString (date, fmt = 'yyyy-MM-dd') {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + '').substr(4 - RegExp.$1.length)
    )
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
  }
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + ''
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? str : padLeftZero(str)
      )
    }
  }
  return fmt
}

function getDateStringCh (date) {
  if (!(date instanceof Date)) {
    return ''
  }
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  let hour = date.getHours()
  return `${year}年${month}月${day}日 ${hour}时`
}

function getWeekStartDateAndEndDateRange () {
  let oneDayLong = 24 * 60 * 60 * 1000
  let now = new Date()
  let mondayTime = now.getTime() - (now.getDay() - 1) * oneDayLong
  let sundayTime = now.getTime() + (7 - now.getDay()) * oneDayLong
  let monday = new Date(mondayTime)
  let sunday = new Date(sundayTime)
  let weekRange = [getDateString(monday), getDateString(sunday)]
  return weekRange
}

// ['2024-04-17 14:36:27', '2024-04-24 14:36:27']  默认值
// console.log(this.$getRecentDays()); 页面使用
export function getRecentDays (duration = 7, fmt = 'yyyy-MM-dd hh:mm:ss') {
  let oneDayLong = 24 * 60 * 60 * 1000
  let nowTime = Date.now()
  let pre7DayTime = nowTime - duration * oneDayLong
  let now = new Date(nowTime)
  let pre7Day = new Date(pre7DayTime)
  return [getDateString(pre7Day, fmt), getDateString(now, fmt)]
}

function getMonthStartDateAndDateRange () {
  let oneDayLong = 24 * 60 * 60 * 1000
  let now = new Date()
  let year = now.getFullYear()
  let monthStartDate = new Date(year, now.getMonth(), 1) //当前月1号
  let nextMonthStartDate = new Date(year, now.getMonth() + 1, 1) //下个月1号
  let days =
    (nextMonthStartDate.getTime() - monthStartDate.getTime()) / oneDayLong //计算当前月份的天数
  let monthEndDate = new Date(year, now.getMonth(), days)
  let monthRange = [getDateString(monthStartDate), getDateString(monthEndDate)]
  return monthRange
}

function padLeftZero (str) {
  return ('00' + str).substr(str.length)
}

function resetForm (refName) {
  this.$refs[refName] && this.$refs[refName].resetFields()
}

export function debounce (func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在,重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

//  console.log(this.$randomUUID());
// 1713940662895.5952  数据数
function randomUUID () {
  return Date.now() + Math.random() + ''
}

const resetTimer = (timer) => {
  if (timer) {
    clearTimeout(timer)
    timer = null
  }
}


// ['2024-04-17 00:00:00', '2024-04-24 23:59:59']  开始时间结束时间
export function todayTimer (duration = 7, fmt = 'yyyy-MM-dd') {
  let oneDayLong = 24 * 60 * 60 * 1000
  let nowTime = Date.now()
  let pre7DayTime = nowTime - duration * oneDayLong
  let now = new Date(nowTime)
  let pre7Day = new Date(pre7DayTime)
  return [
    getDateString(pre7Day, fmt) + ' ' + '00:00:00',
    getDateString(now, fmt) + ' ' + '23:59:59',
  ]
}

// 今年的起始时间 和结束时间 ['2024-01-01 00:00:00', '2024-12-31 23:59:59']
export function ofYear () {
  const startOfYear = moment().startOf('year').format('YYYY-MM-DD 00:00:00');
  const endOfYear = moment().endOf('year').format('YYYY-MM-DD 23:59:59');
  return [startOfYear, endOfYear]
}

//  这个月的开始结束时间 ['2024-04-01 00:00:00', '2024-04-30 23:59:59']
export function ofMonth () {
  const startOfMonth = moment().startOf('month').format('YYYY-MM-DD 00:00:00'); // 本月的起始时间
  const endOfMonth = moment().endOf('month').format('YYYY-MM-DD 23:59:59'); // 本月的结束时间
  return [startOfMonth, endOfMonth]
}

// 上传json;模板
export function funDownload (content, filename) {
  // 创建隐藏的可下载链接
  const eleLink = document.createElement('a')
  eleLink.download = filename
  eleLink.style.display = 'none'
  // 字符内容转变成blob地址
  let blob = new Blob([content])
  eleLink.href = URL.createObjectURL(blob)
  // 触发点击
  document.body.appendChild(eleLink)
  eleLink.click()
  // 然后移除
  document.body.removeChild(eleLink)
}

// 对象转json字符串
export function objToJson (obj) {
  let newObj = {}
  for (let key in obj) {
    if (key === 'id') {
      newObj[key] = obj[key]
      continue
    }
    newObj[key] = JSON.stringify(obj[key])
  }
  return newObj
}
// 打印
export function print (id) {
  var bdhtml = window.document.body.innerHTML
  var jubuData = document.getElementById(id).innerHTML
  window.document.body.innerHTML = jubuData
  var style = document.createElement('style');
  style.innerHTML = `
    @media print {
      @page {
        size: auto;
        margin: 5mm;
      }
      
      body {
        margin: 0;
      }
      .no-print {
        display: none;
      }
      .el-divider {
        border: 1px solid #dcdfe6;
        margin: 24px 0; 
      }
    }
  `;
  document.head.appendChild(style);


  const table = document.querySelectorAll(".el-table__header,.el-table__body,.el-table__footer");
  for (let i = 0; i < table.length; i++) {
    const tableItem = table[i];
    tableItem.style.width = '100%';
    const child = tableItem.childNodes;
    for (let j = 0; j < child.length; j++) {
      const element = child[j];
      if (element.localName == 'colgroup') {
        element.innerHTML = '';
      }
    }
  }
  window.print()
  location.reload()

  document.head.removeChild(style);

  window.document.body.innerHTML = bdhtml
}

// 打印图片
export function printCanvas (id, i) {
  var oldstr = document.body.innerHTML // 获取当前页面内容用以还原
  var div_print = document.getElementById(id) // 获取要打印部分的内容
  var cv = document.getElementsByTagName('canvas')[i] //获取canvas
  var resImg = document.getElementById(id) //获取包裹canvas的标签
  // 将canvas转为图片
  // var context = cv.getContext("2d")
  var img = new Image()
  var strDataURI = cv.toDataURL('image/png')
  img.src = strDataURI
  // 图片加载完成之后
  img.onload = function () {
    // 执行打印
    console.log(img);
    setTimeout(function () {
      resImg.innerHTML = `<img src="${strDataURI}">` // 用图片替代canvas
      var newstr = div_print.innerHTML
      document.body.innerHTML = newstr // 将页面内容改为修改后的内容
      window.print() // 打印
      window.location.reload() // 重新加载页面
      document.body.innerHTML = oldstr // 将页面内容还原
    }, 1000)
  }
}
// 下载echarts为图片
export function exportpic (chartInstance, name = 'charts') {
  let picInfo = chartInstance.getDataURL({
    type: 'png',
    pixelRatio: 2,  //放大两倍下载,之后压缩到同等大小展示。解决生成图片在移动端模糊问题
    backgroundColor: '#fff'
  });//获取到的是一串base64信息

  const elink = document.createElement('a');
  elink.download = name + '.png';
  elink.style.display = 'none';
  elink.href = picInfo;
  document.body.appendChild(elink);
  elink.click();
  URL.revokeObjectURL(elink.href); // 释放URL 对象
  document.body.removeChild(elink)
}

// 复制
export function copyText (row, column, cell, event) {
  // 双击复制
  let save = function (e) {
    e.clipboardData.setData('text/plain', event.target.innerText);
    e.preventDefault();  //阻止默认行为
  }
  document.addEventListener('copy', save);//添加一个copy事件
  document.execCommand("copy");//执行copy方法
  this.$message({ message: '复制成功', type: 'success' })//提示
}

// ['2024-04-23 14:39:48', '2024-04-24 14:39:48'] 
export function getDefaultTimeRange (type = "real", val, fmt = 'yyyy-MM-dd hh:mm:ss') {
  let start = new Date()
  if (type === 'real') {
    start.setDate(start.getDate() - (val ? val : 1))
  }
  if (type === 'hour') {
    start.setDate(start.getDate() - (val ? val : 1))
  }
  if (type === 'day') {
    start.setMonth(start.getMonth() - (val ? val : 1))
  }
  if (type === 'week') {
    start.setMonth(start.getMonth() - (val ? val : 3))
  }
  if (type === 'month') {
    start.setFullYear(start.getFullYear() - (val ? val : 1))
  }
  if (type === 'quarter') {
    val = val || 3; // 如果val未提供,则默认为3
    start.setFullYear(start.getFullYear() - Math.floor(val / 4));
    start.setMonth(start.getMonth() - (val % 4) * 3);
  }
  if (type === 'year') {
    start.setFullYear(start.getFullYear() - (val ? val : 10))
  }
  return [getDateString(start, fmt), getDateString(new Date(), fmt)]
}

// ['2024-04-24 00:00:00', '2024-04-24 23:59:59']  一天结束或开始  
export function getDefaultDayRange (type = "real", fmt = 'yyyy-MM-dd hh:mm:ss') {
  let start = new Date()
  let end = new Date()
  if (type === 'real') {
    start.setDate(start.getDate())
    end.setDate(start.getDate())
  }
  if (type === 'hour') {
    start.setDate(start.getDate())
    end.setDate(start.getDate())
  }
  if (type === 'day') {
    start.setDate(1)
    end.setMonth(end.getMonth() + 1)
    end.setDate(0)
  }
  if (type === 'month') {
    start.setDate(1)
    start.setMonth(0)
    end.setFullYear(end.getFullYear() + 1)
    end.setMonth(0)
    end.setDate(0)
  }
  return [getDateString(start, fmt).split(' ')[0] + ' 00:00:00', getDateString(end, fmt).split(' ')[0] + ' 23:59:59']
}


// 最近几个月 ['2023-10-31 00:00:00', '2024-04-30 23:59:59'] 
//  console.log(this.$recentMonths('month',6));
export function recentMonths (type, val) {
  const now = moment();
  if (type == 'day') {
    const startDate = now.clone().subtract(val - 1, 'days').startOf('day');
    const endDate = now.clone().endOf('day').hours(23).minutes(59).seconds(59);
    const dayRange = [startDate.format('YYYY-MM-DD HH:mm:ss'), endDate.format('YYYY-MM-DD HH:mm:ss')];
    return dayRange;
  }
  if (type == 'week') {
    const weeksAgo = now.clone().subtract(val - 1, 'weeks').startOf('isoWeek');
    const thisWeekEnd = now.clone().endOf('week').hours(23).minutes(59).seconds(59);
    const recentWeeksRange = [weeksAgo.format('YYYY-MM-DD HH:mm:ss'), thisWeekEnd.format('YYYY-MM-DD HH:mm:ss')];
    // console.log(recentWeeksRange);
    return recentWeeksRange;
  }
  if (type == 'month') {
    const sixMonthsAgo = now.clone().subtract(val, 'months').endOf('month').startOf('day');
    const thisMonthEnd = now.clone().endOf('month').hours(23).minutes(59).seconds(59);
    const recentSixMonthsRange = [
      sixMonthsAgo.format('YYYY-MM-DD HH:mm:ss'),
      thisMonthEnd.format('YYYY-MM-DD HH:mm:ss')
    ]
    return recentSixMonthsRange
  }
}

// 参数为秒   返回时间
// console.log(this.$timeRangeFormat(600));   10分钟
export function timeRangeFormat (seconds) {
  const timeUnits = [
    {
      label: '天',
      value: Math.floor(seconds / (24 * 3600))
    },
    {
      label: '小时',
      value: Math.floor((seconds % (24 * 3600)) / 3600)
    },
    {
      label: '分钟',
      value: Math.floor((seconds % 3600) / 60)
    },
    {
      label: '秒',
      value: Math.floor(seconds % 60)
    }
  ]

  return timeUnits.filter(v => v.value > 0).map(item => `${item.value}${item.label}`).join('').trim()
}

// {startDateTime: '2023-03-03 00:00:00', endDateTime: '2023-03-03 23:59:59'}
// console.log(this.$timeRange('day','2023-03-03'));
export function timeRange (type, val) {
  let startDateTime, endDateTime;
  switch (type) {
    case 'hour':
      startDateTime = moment(val).startOf('hour');
      endDateTime = moment(val).endOf('hour');
      break;
    case 'day':
      startDateTime = moment(val).startOf('day');
      endDateTime = moment(val).endOf('day');
      break;
    case 'week':
      let value = val.toString()
      const weekYear = value.substring(0, 4)
      const weekNumber = value.substring(4, 6)
      startDateTime = moment().isoWeekYear(parseInt(weekYear)).isoWeek(parseInt(weekNumber)).startOf('isoWeek');
      endDateTime = moment().isoWeekYear(parseInt(weekYear)).isoWeek(parseInt(weekNumber)).endOf('isoWeek');
      break;
    case 'month':
      startDateTime = moment(val, "YYYY-MM").startOf('month');
      endDateTime = moment(val, "YYYY-MM").endOf('month');
      break;
    case 'quarter':
      let valSeason = val.toString()
      const year = valSeason.substring(0, 4)
      const quarter = valSeason.substring(4, 5)
      startDateTime = moment().quarter(quarter).year(year).startOf('quarter');
      endDateTime = moment().quarter(quarter).year(year).endOf('quarter');
      break;
    case 'year':
      startDateTime = moment(val, "YYYY").startOf('year');
      endDateTime = moment(val, "YYYY").endOf('year');
      break;
    default:
      return;
  }
  startDateTime = startDateTime.format("YYYY-MM-DD HH:mm:ss");
  endDateTime = endDateTime.format("YYYY-MM-DD HH:mm:ss");
  return { startDateTime, endDateTime };
}
export function timeFormatting (type, val) {
  if (type == 'hour') {
    let hour = moment().set({ hour: val, minute: 0, second: 0, millisecond: 0 }).format('YYYY-MM-DD HH');
    return hour
  } else if (type == 'day') {
    let day = moment().date(val).format('YYYY-MM-DD');
    return day
  } else if (type == 'month') {
    let month = moment(val, 'MM').format('YYYY-MM');
    return month
  }
}
//  console.log(this.$timeFormatType('day', '2023123')); 2023-12-03
export function timeFormatType (type, val) {
  if (type == 'hour') {

    let [year, month, date, hour] = String(val).split(/(\d{4})(\d{2})(\d{2})(\d{2})/).slice(1);
    // 创建moment对象并设置时间
    let momentDate = moment().set({ year: parseInt(year), month: parseInt(month) - 1, date: parseInt(date), hour: parseInt(hour), minute: 0, second: 0, millisecond: 0 });
    // 格式化时间
    let hourVal = momentDate.format('YYYY-MM-DD HH');

    return hourVal
  } else if (type == 'day') {
    let day = moment(val, 'YYYYMMDD').format('YYYY-MM-DD');
    return day
  } else if (type == 'month') {
    const month = moment(val, 'YYYYMM').format('YYYY-MM');
    return month
  } else if (type == 'year') {
    const year = moment(val, 'YYYY').format('YYYY');
    return year
  } else if (type == 'week') {
    const weekYear = val.toString().substring(0, 4);
    const weekNum = val.toString().substring(4);
    const startDate = moment(`${weekYear}-01-01`).add((weekNum) * 7, 'days').startOf('isoWeek');
    let week = startDate.format('YYYY-WW');
    return week
  } else if (type == 'quarter') {
    const quarterYear = val.toString().substring(0, 4);
    const quarterNum = val.toString().substring(4);

    // 计算季度的第一天日期
    const startDate = moment(`${quarterYear}-01-01`).add((quarterNum - 1) * 3, 'months').startOf('month');

    let quarter = startDate.format('YYYY-Q');
    return quarter
  }
}

// console.log(this.$tenMonthsAgo(24, 'month'));  
// ['2022-04', '2024-04']
export function tenMonthsAgo (val, type) {
  if (type == 'hour') {
    return hour
  } else if (type == 'day') {
    return day
  } else if (type == 'month') {
    const tenMonthsAgo = moment().subtract(val, 'months').format('YYYY-MM');
    const currentMonth = moment().format('YYYY-MM');
    const month = [tenMonthsAgo, currentMonth];
    return month
  }
}
export function tenMonthsHistory (val, type) {
  if (type == 'hour') {
    return hour
  } else if (type == 'day') {
    return day
  } else if (type == 'month') {
    const tenMonthsAgo = moment().subtract(val, 'months').format('YYYY-MM');
    const currentMonth = moment().subtract(1, 'months').format('YYYY-MM');
    const month = [tenMonthsAgo, currentMonth];
    return month
  }
}

// 20240101   console.log(this.$timeTypeFormatting('day', '2024-01-01'),);
export function timeTypeFormatting (type, value) {
  switch (type) {
    case 'hour':
      return value.substring(0, 13).replace(/[- :]/g, "");
      break;
    case 'day':
      return value.replace(/[- :]/g, "");
      break;
    case 'week':
      return (moment(value).isoWeekYear() + ' ' + moment(value).isoWeek()).replace(/[- :]/g, "");
      break;
    case 'month':
      return value.replace(/[- :]/g, "");
      break;
    case 'year':
      return value.replace(/[- :]/g, "");
      break;
    default: '';
  }
}



export function getBase64 (file) {
  return new Promise(function (resolve, reject) {
    const reader = new FileReader()
    let imgResult = ''
    reader.readAsDataURL(file)
    reader.onload = function () {
      imgResult = reader.result
    }
    reader.onerror = function (error) {
      reject(error)
    }
    reader.onloadend = function () {
      resolve(imgResult)
    }
  })
}

export function getEmpty (val) {
  if (val !== null && val !== false && val !== undefined && val !== NaN && val !== '') {
    return val
  } else {
    return '-'
  }
}
export function getEmptyUnit (val, unit) {
  if (val !== null && val !== false && val !== undefined && val !== NaN && val !== '' && val != '0.00' && val !== 0 && val && val !== 'NaN') {
    return unit
  } else {
    return ''
  }
}


export function findObjectByValue (arr, val) {
  let result = [];

  function search (arr, parentObjects = []) {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].id === val) {
        // 找到匹配项,将当前对象和所有父级对象都添加到结果数组
        result.push(...parentObjects, arr[i]);
      }
      if (arr[i].childs && arr[i].childs.length > 0) {
        // 递归搜索子对象,将当前对象添加到父级对象数组中
        search(arr[i].childs, [...parentObjects, arr[i]]);
      }
    }
  }

  search(arr);
  return result;
}





export default {
  install (vue) {
    this.addGlobalMethods(vue)
  },
  addGlobalMethods (vue) {
    vue.prototype.$random = random
    vue.prototype.$resetForm = resetForm
    vue.prototype.$randomOne = randomOne
    vue.prototype.$getDateString = getDateString
    vue.prototype.$getRecentDays = getRecentDays
    vue.prototype.$getWeekStartDateAndEndDateRange =
      getWeekStartDateAndEndDateRange
    vue.prototype.$getMonthStartDateAndDateRange = getMonthStartDateAndDateRange
    vue.prototype.$debounce = debounce
    vue.prototype.$getDateStringCh = getDateStringCh
    vue.prototype.$randomUUID = randomUUID
    vue.prototype.$resetTimer = resetTimer
    vue.prototype.$todayTimer = todayTimer
    vue.prototype.$funDownload = funDownload
    vue.prototype.$objToJson = objToJson
    vue.prototype.$print = print
    vue.prototype.$printCanvas = printCanvas
    vue.prototype.$exportpic = exportpic
    vue.prototype.$copyText = copyText
    vue.prototype.$getDefaultTimeRange = getDefaultTimeRange
    vue.prototype.$timeRangeFormat = timeRangeFormat
    vue.prototype.$timeRange = timeRange
    vue.prototype.$ofYear = ofYear
    vue.prototype.$ofMonth = ofMonth
    vue.prototype.$getDefaultDayRange = getDefaultDayRange
    vue.prototype.$timeFormatting = timeFormatting
    vue.prototype.$getBase64 = getBase64
    vue.prototype.$getEmpty = getEmpty
    vue.prototype.$getEmptyUnit = getEmptyUnit
    vue.prototype.$findObjectByValue = findObjectByValue
    vue.prototype.$tenMonthsAgo = tenMonthsAgo
    vue.prototype.$timeTypeFormatting = timeTypeFormatting
    vue.prototype.$timeFormatType = timeFormatType
    vue.prototype.$tenMonthsHistory = tenMonthsHistory
    vue.prototype.$recentMonths = recentMonths
  },
}

总结 

到此这篇关于vue各种时间类型转换的文章就介绍到这了,更多相关vue时间类型转换内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文