vue前端常用工具类汇总

这篇文章介绍了如何在JavaScript中编写一些常用的工具类函数,如文件大小单位转换、从URL获取参数、使用正则表达式、日期格式化、处理时间和语言以及实现防抖和节流功能,提升代码复用性和性能管理。
摘要由CSDN通过智能技术生成

总结的工具类,可直接复用

utils文件夹中的util.js编写公共工具类

const initUtil = {}

Byte 转 KB/MB/GB

initUtil.getfilesize = (size = 0,) => {
	if (!size) return '0.00GB';
	const num = 1000.00; //byte
	if (size < num)
		return size + "B";
	if (size < Math.pow(num, 2))
		return (size / num).toFixed(2) + "KB"; //kb
	if (size < Math.pow(num, 3))
		return (size / Math.pow(num, 2)).toFixed(2) + "MB"; //M
	if (size < Math.pow(num, 4))
		return (size / Math.pow(num, 3)).toFixed(2) + "GB"; //G
}

知识点:
1、Math.pow(base, exponent):Math.pow(2, 3),2 的 3 次方是 8。
2、toFixed(2) 格式化数字,返回字符串类型,当前保留数字后两位

获取url指定参数

  1. 使用 URLSearchParams 对象:
initUtil.getUrlParam = (name) => {
	// 假设 URL 为:https://example.com/page?name=John&age=25
	// 创建 URLSearchParams 对象,将 URL 查询参数解析到该对象中
	const urlParams = new URLSearchParams(window.location.search);
	// 获取指定参数的值
	return urlParams.get(name)
}
  1. 使用正则表达式:
initUtil.getUrlParam = (name,url) => {
	name = name.replace(/[\[\]]/g, "\\$&");
    const regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url || window.location.href);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

getUrlParam('name')

知识点

1、正则表达式(Regular Expression): 正则表达式用于在 URL 中匹配指定的参数名,并捕获对应的参数值。 name = name.replace(/[[]]/g, “\$&”); 这一行用于将参数名中的方括号进行转义,确保正则表达式匹配正确。

2、RegExp 对象: const regex = new RegExp(“[?&]” + name + “(=([^&#]*)|&|#|$)”); 创建了一个正则表达式对象,该正则表达式匹配 URL 查询字符串中指定参数名的模式。

3、exec 方法: regex.exec(url || window.location.href); 使用 exec 方法在URL中执行正则表达式,返回匹配的结果数组。结果数组中,results[0] 包含整个匹配项,results[2] 包含参数值

日期格式化

initUtil.dateFormat = (date, format = 'YYYY-MM-DD HH:mm:ss') => {
	const config = {
		YYYY: date.getFullYear(),
		MM: date.getMonth() + 1,//getMonth() 方法根据本地时间返回指定日期的月份(从 0 到 11)
		DD: date.getDate(),
		HH: date.getHours(),
		mm: date.getMinutes(),
		ss: date.getSeconds(),
	}
	for (const key in config) {
		format = format.replace(key, config[key])
	}
	return format
}

知识点:

replace方法的基本语法是:

newString = originalString.replace(searchValue, replaceValue);
  • originalString 是原始字符串。
  • searchValue 是要被替换的子字符串或正则表达式。
  • replaceValue 是替换的内容。

如果 searchValue 是一个字符串,只会替换第一次出现的匹配项。
如果 searchValue 是一个正则表达式,会替换所有匹配项。
返回的是一个新的字符串,原始字符串并没有被改变

以下是一些示例:

let originalString = "Hello, world! Hello, universe!";
let newString = originalString.replace("Hello", "Hi");
console.log(newString);
// 输出: "Hi, world! Hello, universe!"

let regex = /Hello/g;  // 使用正则表达式,全局匹配
newString = originalString.replace(regex, "Hi");
console.log(newString);
// 输出: "Hi, world! Hi, universe!"

返回时间段

initUtil.getTimeState = (time, lang) => {
	let text = ``;
	if (time) {
		// 获取当前小时
		let hours = Number(time.split(':')[0]);
		// 设置默认文字
		
		// 判断当前时间段
		if (lang !== 'en') {
			if (hours >= 0 && hours <= 11) {
				text = `上午`;
			} else {
				text = `下午`;
			}
		} else {
			if (hours >= 0 && hours <= 11) {
				text = `AM`;
			} else {
				text = `PM`;
			}
		}
	}
	// 返回当前时间段对应的状态
	return text;
}

防抖

initUtil.debounce = (fn, delay = 500) => {
	let timer
	return function () {
		clearTimeout(timer)
		timer = setTimeout(() => {
			fn.apply(this, arguments)
		}, delay)
	}
}

节流

initUtil.throttle = (fn, delay = 500) => {
	let timer
	return function () {
		if (!timer) {
			clearTimeout(timer)
			timer = setTimeout(() => {
				fn.apply(this, arguments)
				timer = null
			}, delay)
		}
	}
}
  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值