分享几个项目中常用的js封装

245 阅读1分钟

「这是我参与2022首次更文挑战的第23天,活动详情查看:2022首次更文挑战

大家好,我是 摸鱼小公举,真正的强者,不会怨天尤人,如果想不被别人看轻,你就只有付出比别人多十倍百倍的努力,才能站的比别人更高。上一篇文章是 uni-app 实现微信小程序的表单使用 ;今天我来分享几个项目中常用的js封装。

日期格式的转化(时间戳转化)

在页面中常常可以看见日期时间的展示,是我们做项目时最长用到的。

const formatTime = stamps => {
	let _date = new Date(stamps * 1000);
	let Y = _date.getFullYear();
	let M = (_date.getMonth() + 1) < 10 ? '0' + (_date.getMonth() + 1) : (_date.getMonth() + 1);
	let D = _date.getDate() < 10 ? '0' + _date.getDate() : _date.getDate();
	let h = _date.getHours() < 10 ? '0' + _date.getHours() : _date.getHours();
	let m = _date.getMinutes() < 10 ? '0' + _date.getMinutes() : _date.getMinutes();
	let s = _date.getSeconds();
	return Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s;
}

深拷贝

像这个深拷贝我是一般表单数据提交的时候比较多,提交数据的时候可能会改变data里的form对象的值,这时可能会影响页面数据的显示或者下一次表单的提交。所以像这种时候需要用到深拷贝方法,source这个参数是要传需要深拷贝的数据。

export function deepCopy(source) {  
  if (typeof source === 'object') {
    const sourceCopy = source instanceof Array ? [] : {}
    for (const item in source) {
      if (!source[item]) {
        sourceCopy[item] = source[item]
      } else {
        sourceCopy[item] =
          typeof source[item] === 'object'
            ? deepCopy(source[item])
            : source[item]
      }
    }
    return sourceCopy
  }
  return source
}

倒计时

倒计时也是我们常常用到的功能,这里直接封装好了,简直不要太方便了,这里的time参数传的时时间戳的秒数。

export function formatTimeFunc(time) {
  let h = parseInt((time / 60 / 60) % 24)
  let m = parseInt((time / 60) % 60)
  let s = parseInt(time % 60)
  h = h > 9 ? h : '0' + h
  m = m > 9 ? m : '0' + m
  s = s > 9 ? s : '0' + s
  if (time <= 0) {
    return '0秒'
  }
  if (h == 0 && m == 0) {
    return `${s}秒`
  } else if (h == 0) {
    return `${m}${s}秒`
  } else {
    return `${h}${m}${s}秒`
  }
}

获取url参数的方法

像这个方法我是H5页面用的比较多,记得这个url还是安卓或者IOSapp携带参数跳转到H5页面才用到这个方法。

function getParams(url) {
   const res = {};
    if (url.includes("?")) {
      const str = url.split("?")[1];
      const arr = str.split("&");
      arr.forEach((item) => {
      const key = item.split("=")[0];
      const val = item.split("=")[1];
      res[key] = decodeURIComponent(val); // 解码
      });
      }
      return res;
}
//运用
const user = getParams(
 "http://www.baidu.com?user=%E9%98%BF%E9%A3%9E&age=16"
);
console.log(user, "params"); // {user: '阿飞', age: '16'} 'params'

判断变量是否为空的方法

这也是项目中常用的,毕竟判断一下是否为空比较保险起见。source参数传入的是需要判断为空的变量。

export function isEmpty(source) {
  if (typeof source === "undefined") return true
  if (typeof source === "string") return source.trim(" ").length === 0
  if (source === null) return true
  if (isArray(source) && source.length === 0) return true
  if (isObject(source) && Object.keys(source).length === 0) return true
  return false
}

结语:

这些方法是从我项目中提取出来分享的,好了文章到此就结束了,欢迎大家( 点赞+评论+关注 ) 有问题可以来互相交流一下。希望这篇文章对大家有帮助,也希望大家多多支持我,今天是我参与2022首次更文挑战的第23天,加油!坚持就是胜利。