为了账号安全,请及时绑定邮箱和手机立即绑定

utils封装汇总(待增加)

标签:
Vue.js

vue项目中经常会自己封装一些函数,在项目中方便多处调用.这里给出一部分我自己封装以及收集的仅供参考.

//util.js 常用汇总/*
@1 local 浏览器数据存储方式封装 set  get clear
@2 joinReqParams 拼接请求参数
@3 deviceType  移动设备的类型
@4 formDate 时间转换  
@5 remainTime格式化剩余时间   
@6 timeDiff 计算两段时间差 
@7 dateGet 获取时间汇总
*///@1 +++++++++ 浏览器储存数据方式封装,//默认使用localstorage存储,若浏览器不支持则用cookie存储 +++++++++++let local = {
  set(key, value) {    if (checkLocalStorage()) {      window.localStorage.setItem(key, value);
    } else {      let Days = 30;      let exp = new Date();
      exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);      document.cookie = key + '=' + escape(value) + ';expires=' + exp.toGMTString();
    }
  },
  get(key) {    if (checkLocalStorage()) {      return window.localStorage.getItem(key) ? window.localStorage.getItem(key) : null;
    } else {      return getCookie(key);
    }
  },
  clear(key) {    if (checkLocalStorage()) {
      key ? window.localStorage.removeItem(key) : window.localStorage.clear();
    } else {      let exp = new Date();
      exp.setTime(exp.getTime() - 1);      let cval = getCookie(key);      if (cval != null) document.cookie = key + '=' + cval + ';expires=' + exp.toGMTString();
    }
  }
};function checkLocalStorage() {  //确认是否支持Localstorage
  return window.localStorage && (window.localStorage.setItem('a', 123), window.localStorage.getItem('a') == 123)
    ? true
    : false;
}function getCookie(name) {  let arr,
    reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)');  if ((arr = document.cookie.match(reg))) return unescape(arr[2]);  else return null;
}//@2 joinReqParams 拼接请求参数function joinReqParams(obj) {  let params = Object.values(obj).reduce((a, b, i) => `${a}${Object.keys(obj)[i]}=${b}&`, '?');  return params.substring(0, params.length - 1);
}//@3 deviceType  移动设备的类型  文件引用有误暂时注释/*
const UA = navigator.userAgent;
let deviceType = {
  isAndroid: /android|adr/gi.test(UA),
  isIos: /iphone|ipod|ipad/gi.test(UA) && !this.isAndroid,
  isWeixin: /MicroMessenger/gi.test(UA),
  isQQ: /QQ\/\d/gi.test(UA),
  isClient: this.isWeixin || this.isQQ,
  isChrome: /Chrome\/([\d.]+)/gi.test(UA) || /CriOS\/([\d.]+)/gi.test(UA),
  isIosWebview: !this.isChrome && /(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/gi.test(UA)
};
*/// @4  +++++ 时间转换封装 ++++++ "YY年MM月DD日 hh时mm分ss秒"function formDate(time = new Date(), format = 'YY-MM-DD hh:mm:ss') {  const v_list = {    //年
    YY: time.getFullYear(),    //月
    MM: time.getMonth() + 1 < 10 ? '0' + (time.getMonth() + 1) : time.getMonth() + 1,    //日
    DD: time.getDate() < 10 ? '0' + time.getDate() : time.getDate(),    //时
    hh: time.getHours() < 10 ? '0' + time.getHours() : time.getHours(),    //分
    mm: time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes(),    //秒
    ss: time.getSeconds() < 10 ? '0' + time.getSeconds() : time.getSeconds()
  };  return [
    {      id: format.indexOf('YY'),      v: v_list.YY + format.charAt(format.indexOf('YY') + 2)
    },
    {      id: format.indexOf('MM'),      v: v_list.MM + format.charAt(format.indexOf('MM') + 2)
    },
    {      id: format.indexOf('DD'),      v: v_list.DD + format.charAt(format.indexOf('DD') + 2)
    },
    {      id: format.indexOf('hh'),      v: v_list.hh + format.charAt(format.indexOf('hh') + 2)
    },
    {      id: format.indexOf('mm'),      v: v_list.mm + format.charAt(format.indexOf('mm') + 2)
    },
    {      id: format.indexOf('ss'),      v: v_list.ss + format.charAt(format.indexOf('ss') + 2)
    }
  ]
    .filter(v => v.id > -1)
    .reduce((a, b) => a + b.v, '');
}//@5 格式化剩余时间function remainTime(num, format = 'hh:mm:ss') {  if (!num) return '00:00:00';
  num /= 1000;  let h = parseInt(num / 3600),
    m = parseInt(num / 60),
    s = parseInt(num % 60);  const v_list = {    //时
    hh: (h > 60 ? (h -= 60) : h) < 10 ? '0' + h : h,    //分
    mm: (m > 60 ? (m -= 60) : m) < 10 ? '0' + m : m,    //秒
    ss: (s > 60 ? (s -= 60) : s) < 10 ? '0' + s : s
  };  return [
    {      id: format.indexOf('hh'),      v: v_list.hh + format.charAt(format.indexOf('hh') + 2)
    },
    {      id: format.indexOf('mm'),      v: v_list.mm + format.charAt(format.indexOf('mm') + 2)
    },
    {      id: format.indexOf('ss'),      v: v_list.ss + format.charAt(format.indexOf('ss') + 2)
    }
  ]
    .filter(v => v.id > -1)
    .reduce((a, b) => a + b.v, '');
}//@6 timeDiff 计算两段时间差 时分秒 startTime 这里是时间类型 ==>'2018/05/01 00:00:00'//   endTime 这里是new Date()出来的  一般是即时的function timeDiff(startTime, endTime) {  let date1 = startTime; //开始时间
  let date2 = endTime; //结束时间
  let date3 = date2.getTime() - new Date(date1).getTime();  //计算出相差天数
  let days = Math.floor(date3 / (24 * 3600 * 1000));  //计算出小时数
  let leave1 = date3 % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
  let hours = Math.floor(leave1 / (3600 * 1000)) + days * 24; //这里计算时间差要以小时为单位
  let hours2 = Math.floor(leave1 / (3600 * 1000));  if (hours < 10) hours = `0${hours}`;  //计算相差分钟数
  let leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
  let minutes = Math.floor(leave2 / (60 * 1000));  if (minutes < 10) minutes = `0${minutes}`;  //计算相差秒数
  let leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
  let seconds = Math.round(leave3 / 1000);  if (seconds < 10) seconds = `0${seconds}`;  const timeDiffrence = `${hours}:${minutes}:${seconds}`; //时间差包括天数
  const timeDiffrence2 = `${days}天${hours}时${minutes}分${seconds}秒`;  return timeDiffrence;
}//@7 dateGet 获取日期 +++++++++++ 获取日期汇总 ++++++++++++/*
let date = {
  datepick:computeDay(dates), 天数加减,返回当天的日期
  dateCurrent:getCurrentWeek(),  获取本周的日期
  dateLastWeek:getLastWeek(), 获取上周的时间
  dateMonth:computeMonth(),月份加减,返回第一天和最后一天的日期
  dateCurrMonth:getCurrentMonth(),本月的时间
  dateLastMonth:getLastMonth(),返回上月的时间
}
*/// 天数加减,m返回当天的日期function computeDay(dates = 0) {  let t = new Date();
  t.setDate(t.getDate() + dates);  let y = t.getFullYear();  let m = t.getMonth() + 1;  let d = t.getDate();  return `${y}-${m < 10 ? '0' + m : m}-${d < 10 ? '0' + d : d}`;
}// 获取本周的时间function getCurrentWeek() {  let d = new Date();  let day = d.getDay();  let c = day != 0 ? day - 1 : 6;  return [computeDay(c - 6), computeDay(c)];
}// 获取上周的时间function getLastWeek() {  let d = new Date();  let day = d.getDay();  let c = day != 0 ? day - 1 : 6;  return [computeDay(c - (6 + 7)), computeDay(c - 7)];
}// 月份加减,返回第一天和最后一天日期function computeMonth(months = 0) {  let t = new Date();  if (months) {
    t.setMonth(t.getMonth() + months);
  }  let y = t.getFullYear();  let m = t.getMonth() + 1;  let d = 0;  if (~[1, 3, 5, 7, 8, 10, 12].indexOf(m)) {
    d = 31;
  } else if (m == 2) {    // 判断是否为闰年(能被4整除且不能被100整除 或 能被100整除且能被400整除)
    if ((y % 4 == 0 && y % 100 != 0) || (y % 100 == 0 && y % 400 == 0)) {
      d = 29;
    } else {
      d = 28;
    }
  } else {
    d = 30;
  }  return [`${y}-${m < 10 ? '0' + m : m}-${1}`, `${y}-${m < 10 ? '0' + m : m}-${d < 10 ? '0' + d : d}`];
}// 获取本月的时间function getCurrentMonth() {  return computeMonth();
}// 获取上月的时间function getLastMonth() {  return computeMonth(-1);
}



作者:会拐弯的蜗牛
链接:https://www.jianshu.com/p/73e1ee754e88


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消