前端新手Vue3+Vite+Ts+Pinia+Sass项目指北系列文章 —— 第十二章 常用工具函数 (Utils配置)

news/发布时间2024/5/18 8:14:42

前言

在项目开发中,我们经常会使用一些工具函数,也经常会用到例如loadsh等工具库,但是这些工具库的体积往往比较大,如果项目本身已经引入了这些工具库,那么我们就没有必要再引入一次,所以我们需要自己封装一些工具函数,来简化我们的开发。

一、通用类工具函数

src/utils目录下创建tools文件夹,用于存放通用类工具函数文件。
tools文件下创建index.ts文件

import { ElMessage, MessageHandler } from 'element-plus'/*** @description 文档注册enter事件* @param {Function} cb* @return {void}*/
export function handleEnter(cb: Function): void {if (typeof cb !== 'function')returndocument.onkeydown = (e) => {const ev: KeyboardEventInit = e || window.eventconst keyCode = ev.code || ev.keyCodeif (keyCode === 'Enter' || keyCode === 13)cb()}
}/*** @description 日期格式化* @param {string | number} time {string like:{y}-{m}-{d} {h}:{i}:{s} } pattern* @return {string}*/
export function parseTime(time: string | number, pattern: string) {if (arguments.length === 0 || !time)return nullconst format = pattern || '{y}-{m}-{d}'let dateif (typeof time === 'object') {date = time}else {if (typeof time === 'string' && /^[0-9]+$/.test(time)) {time = Number.parseInt(time)}else if (typeof time === 'string') {time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '')}if (typeof time === 'number' && time.toString().length === 10)time = time * 1000date = new Date(time)}const formatObj: Record<string, string> = {y: date.getFullYear(), // 年m: date.getMonth() + 1, // 月d: date.getDate(), // 日h: date.getHours(), // 时i: date.getMinutes(), // 分s: date.getSeconds(), // 秒a: date.getDay(), // 星期几}const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {let value = formatObj[key]// 注意:getDay()返回的是0表示星期天if (key === 'a')return ['日', '一', '二', '三', '四', '五', '六'][value]if (result.length > 0 && Number(value) < 10)value = `0${value}`return value || 0})return time_str
}/*** @description trim函数* @param {string} str* @return {string}*/
export function trim(str: string): string {return str.replace(/^\s+|\s+$/g, '') // 去除字符串两端的空格
}/*** @description uuid的生成* @return {string}*/
/*** @description 生成UUID* @return {string}*/
export function getUUID(): string {const s: string[] = []const hexDigits = '0123456789abcdef'for (let i = 0; i < 36; i++) {s[i] = hexDigits[Math.floor(Math.random() * 0x10)]}s[14] = '4's[19] = hexDigits[(parseInt(s[19], 16) & 0x3) | 0x8]s[8] = s[13] = s[18] = s[23] = '-'const uuid = s.join('')return uuid
}
// 38673f6b-bacc-4d9b-9330-dd97b7ae238f/*** @description 千分位* @param {string | number} num* @return {void}*/
export function addThousand(num: string | number): string {if (num)num = Number(num).toFixed(2)if ((!num && num !== 0) || num == 'NaN')return '--'const regForm = /(\d{1,3})(?=(\d{3})+(?:$|\.))/gnum = num.toString().replace(regForm, '$1,')return num
}/*** @description 大数值转换和保留n位有效数字* @param {number} num {number} digits* @return {string}*/
export function numberFormatter(num: number, digits: number | undefined): string {const si = [{ value: 1e13, symbol: '亿亿' },{ value: 1e12, symbol: '万亿' },{ value: 1e11, symbol: '千亿' },{ value: 1e10, symbol: '百亿' },{ value: 1e9, symbol: '十亿' },{ value: 1e8, symbol: '亿' },{ value: 1e7, symbol: '千万' },{ value: 1e6, symbol: '百万' },{ value: 1e5, symbol: '十万' },{ value: 1e4, symbol: '万' },{ value: 1e3, symbol: '千' },]for (let i = 0; i < si.length; i++) {if (num >= si[i].value)return (num / si[i].value).toFixed(digits).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, '$1') + si[i].symbol}return num.toString()
}/*** @description 复制方法* @param {string} value 传入要复制的值* @return {string | MessageHandler}*/
export const copy = (value: string): string | MessageHandler => {if (!value)return ElMessage.error('复制失败')const tag = document.createElement('textarea')tag.value = valuedocument.body.appendChild(tag)tag.select()document.execCommand('copy')ElMessage.success('复制成功')tag.remove()return value
}/*** @description 防抖* @param {number} timer* @return {function}*/
export function debounce(timer = 0): (callback: unknown, delay: number) => void {return (callback: unknown, delay: number) => {if (timer)clearTimeout(timer)if (typeof callback === 'function')timer = setTimeout(callback, delay)}
}/*** @description 节流* @param {number} timer* @return {function}*/
export const throttle: (fn: (...args: unknown[]) => void, timer: number) => (...args: unknown[]) => void = (fn, timer = 0) => {let time: number | null = nullreturn (...args: unknown[]) => {if (time)clearTimeout(time)time = setTimeout(() => {fn.apply(this, args)}, timer)}
}

二、文件相关函数

tools文件下创建blobType.ts文件

export const blobType: Record<string, string> = {'aac': 'image/audio/aac','abw': 'application/x-abiword','arc': 'application/x-freearc','avi': 'video/x-msvideo','azw': 'application/vnd.amazon.ebook','bin': 'application/octet-stream','bmp': 'image/bmp','bz': 'application/x-bzip','bz2': 'application/x-bzip2','csh': 'application/x-csh','css': 'text/css','csv': 'text/csv','doc': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document','docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document','eot': 'application/vnd.ms-fontobject','epub': 'application/epub+zip','exe': 'application/x-msdownload','gif': 'image/gif','htm': 'text/html','html': 'text/html','ico': 'image/vnd.microsoft.icon','ics': 'text/calendar','jar': 'application/java-archive','jpeg': 'image/jpeg','jpg': 'image/jpeg','js': 'text/javascript','json': 'application/json','jsonld': 'application/ld+json','mid': 'audio/midi audio/x-midi','midi': 'audio/midi audio/x-midi','mjs': 'text/javascript','mp3': 'audio/mpeg','mpeg': 'video/mpeg','mpkg': 'application/vnd.apple.installer+xml','odp': 'application/vnd.oasis.opendocument.presentation','ods': 'application/vnd.oasis.opendocument.spreadsheet','odt': 'application/vnd.oasis.opendocument.text','oga': 'audio/ogg','ogv': 'video/ogg','ogx': 'application/ogg','otf': 'font/otf','png': 'image/png','pdf': 'application/pdf','ppt': 'application/vnd.ms-powerpoint','pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation','rar': 'application/x-rar-compressed','rtf': 'application/rtf','sh': 'ima','svg': 'image/svg+xml','swf': 'application/x-shockwave-flash','tar': 'application/x-tar','tif': 'image/tiff','tiff': 'image/tiff','ttf': 'font/ttf','txt': 'text/plain','vsd': 'application/vnd.visio','wav': 'audio/wav','weba': 'audio/webm','webm': 'video/webm','webp': 'image/webp','woff': 'font/woff','woff2': 'font/woff2','xhtml': 'application/xhtml+xml','xls': 'application/vnd.ms-excel','xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','xml': 'text/xml','xul': 'application/vnd.mozilla.xul+xml','zip': 'application/zip','3gp': 'video/3gpp','3g2': 'video/3gpp2','7z': 'application/x-7z-compressed',
}

tools文件下创建file.ts文件

import { ElMessage } from 'element-plus'
import { blobType } from './blobType'export function download(file: any, fileType: string, fileName?: string) {if (!fileName) {const timeStr = new Date().getTime()fileName = `${timeStr}`}const type = formatFileType(fileType)if (!type)return ElMessage.warning('暂不支持此格式!')const blob = new Blob([file], { type })const downloadElement = document.createElement('a')const href = window.URL.createObjectURL(blob) // 创建下载的链接downloadElement.href = hrefdownloadElement.download = fileName // 下载后文件名document.body.appendChild(downloadElement)downloadElement.click() // 点击下载document.body.removeChild(downloadElement) // 下载完成移除元素window.URL.revokeObjectURL(href) // 释放掉blob对象
}export function formatFileType(fileFormat: string) {return blobType[fileFormat]
}export function blobToFileReader(blob: any, callback: any) {if (!blob.size)return ElMessage.warning('暂无资源!')if (blob.type !== 'application/json')return callback(blob)const fr: any = new FileReader()fr.onloadend = function () {try {callback(JSON.parse(fr.result))}catch (err) {ElMessage.warning('资源数据有误!')}}fr.readAsText(blob)
}

三、存储相关函数

src/utils目录下创建cache文件夹,用于存放存储类工具函数文件。
cache文件夹下创建index.ts文件

/*** window.localStorage 浏览器永久缓存* @method set 设置永久缓存* @method get 获取永久缓存* @method remove 移除永久缓存* @method clear 移除全部永久缓存*/
export const Local = {// 设置永久缓存set(key: string, val: any) {window.localStorage.setItem(key, JSON.stringify(val))},// 获取永久缓存get(key: string) {const json: any = window.localStorage.getItem(key)return JSON.parse(json)},// 移除永久缓存remove(key: string) {window.localStorage.removeItem(key)},// 移除全部永久缓存clear() {window.localStorage.clear()},
}/*** window.sessionStorage 浏览器临时缓存* @method set 设置临时缓存* @method get 获取临时缓存* @method remove 移除临时缓存* @method clear 移除全部临时缓存*/
export const Session = {// 设置临时缓存set(key: string, val: any) {window.sessionStorage.setItem(key, JSON.stringify(val))},// 获取临时缓存get(key: string) {const json: any = window.sessionStorage.getItem(key)return JSON.parse(json)},// 移除临时缓存remove(key: string) {window.sessionStorage.removeItem(key)},// 移除全部临时缓存clear() {window.sessionStorage.clear()},
}

在这里插入图片描述

总结

工具函数的封装,可以提高代码的复用性,降低维护成本,本文只是介绍了一小部分工具函数的封装,更多的工具函数的封装,可以参考lodash等函数工具库,也可以根据实际需求,封装自己的工具函数。上文中的配置代码可在 github 仓库中直接 copy,仓库路径:https://github.com/SmallTeddy/ProjectConstructionHub。

写在最后

经过一段时间的整理和书写,前端新手Vue3+Vite+Ts+Pinia+Sass项目指北系列文章已经全部更新完了,感谢各位小伙伴的支持与厚爱,文章中可能有一些依赖部分会有所更新,最后依赖版本号请参考仓库中的地址进行对照。前端道路道阻且长,富而杂,多而繁,请各位取长补短,各自努力绽放。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.bcls.cn/uyBX/1158.shtml

如若内容造成侵权/违法违规/事实不符,请联系编程老四网进行投诉反馈email:xxxxxxxx@qq.com,一经查实,立即删除!

相关文章

鸿蒙系统进一步学习(一):学习资料总结,少走弯路

随着鸿蒙Next的计划越来越近&#xff0c;笔者之前的鸿蒙系统扫盲系列中&#xff0c;有很多朋友给我留言&#xff0c;不同的角度的问了一些问题&#xff0c;我明显感觉到一点&#xff0c;那就是许多人参与鸿蒙开发&#xff0c;但是又不知道从哪里下手&#xff0c;因为资料太多&a…

Vi 和 Vim 编辑器

Vi 和 Vim 编辑器 vi 和 vim 的基本介绍 Linux 系统会内置 vi 文本编辑器 Vim 具有程序编辑的能力&#xff0c;可以看做是 Vi 的增强版本&#xff0c;可以主动的以字体颜色辨别语法的正确性&#xff0c;方便程序设计。 代码补完、编译及错误跳转等方便编程的功能特别丰富&…

【超级干货】ArcGIS_空间连接_工具详解

帮助里对空间连接的解释&#xff1a; 根据空间关系将一个要素的属性连接到另一个要素。 目标要素和来自连接要素的被连接属性写入到输出要素类。 如上图所示&#xff0c;关键在于空间关系&#xff0c;只有当两个要素存在空间关系的时候&#xff0c;空间连接才有用武之地。 一…

MySQL 基础知识(四)之表操作

目录 1 约束 2 查看已有表 3 创建表 4 查看表结构 5 修改表 6 删除表 1 约束 主键约束 primary key&#xff1a;唯一&#xff0c;标识表中的一行数据&#xff0c;此列的值不可重复&#xff0c;且不能为 NULL&#xff0c;此外&#xff0c;可以多个列组成主键唯一约束 uniq…

Linix与Windows上使用nc命令测试某一个服务器端口网络是否正常可访问详细安装及测试步骤

一、windows 1、下载nc安装包 https://nszyf.lanzoum.com/ihtqS0v0lwwh 2、下载后解压放置在自己电脑合适的位置&#xff0c;并且配置到环境变量中 3、配置成功环境变量&#xff0c;winr打开运行&#xff0c;输入cmd&#xff0c;回车&#xff0c;打开一个终端测试 测试成功…

腾讯云4核8G12M服务器4c或4h什么意思?8g是什么?

4核8G是云服务器的参数&#xff0c;代表云服务器的硬件配置和网络带宽&#xff0c;4核代表CPU、8G是指内存、12M代表带宽值为12Mbps&#xff0c;腾讯云百科txybk.com以腾讯云轻量应用服务器4核8G12M带宽配置为例&#xff0c;来详细介绍下服务器参数&#xff1a; 4c8g是什么意思…

ARM:AI 的翅膀,还能飞多久?

ARM&#xff08;ARM.O&#xff09;于北京时间 2024 年 2 月 8 日上午的美股盘后发布了 2024 年第三财年报告&#xff08;截止 2023 年 12 月&#xff09;&#xff0c;要点如下&#xff1a; 1、整体业绩&#xff1a;收入再创新高。ARM 在 2024 财年第三季度&#xff08;即 23Q4…

Window系统GPT-SoVITS配置安装

GPT-SoVITS配置安装 GPT-SoVITS配置Python下载以及安装源文件安装依赖 运行整理在安装配置环境时遇到的报错总结 GPT-SoVITS配置 作者链接 Python下载以及安装 版本这里根据教程的版本走即可&#xff0c;这里不会安装python或者不会配置环境的参考我之前的文章 Python 3.9,…

C语言之内存函数

内存函数&#xff1a;通常指的是在编程中用于处理内存操作的函数&#xff0c;这些函数可以用来分配、释放、复制、比较等内存相关的操作。在C语言中&#xff0c;这些内存函数 memcpy()、memmove()、memset()、memcmp() 都需要引用头文件 <string.h>。 1.memcpy函数 mem…

【电路笔记】-感抗

感抗 文章目录 感抗1、概述2、感抗示例13、通过 LR 串联电路的交流电源4、感抗示例25、交流电感器的功率三角形线圈的感抗取决于所施加电压的频率,因为电抗与频率成正比。 1、概述 感抗是电感线圈的一种特性,它抵抗通过它的交流电 (AC) 的变化,类似于电阻中对抗直流电 (DC)…

OpenAI:Sora视频生成模型技术报告(中文)

概述 视频生成模型作为世界模拟器 我们探索视频数据生成模型的大规模训练。具体来说&#xff0c;我们在可变持续时间、分辨率和宽高比的视频和图像上联合训练文本条件扩散模型。我们利用transformer架构&#xff0c;在视频和图像潜在代码的时空补丁上运行。我们最大的模型Sor…

单片机学习笔记---DS18B20温度读取

目录 OneWire.c 模拟初始化的时序 模拟发送一位的时序 模拟接收一位的时序 模拟发送一个字节的时序 模拟接收一个字节的时序 OneWire.h DS18B20.c DS18B20数据帧 模拟温度变换的数据帧 模拟温度读取的数据帧 DS18B20.h main.c 上一篇讲了DS18B20温度传感器的工作原…

js设计模式:职责链模式

作用: 可以处理链式调用的业务逻辑,下一步操作需要上一步操作的处理结果 可以使用职责链模式进行解耦操作,按顺序链向下传递,依次向下查找可以处理的业务逻辑 示例: const wjt (expressage) > {if (expressage 《js设计模式从入门到精通》) {return 快递名称:${express…

C++类和对象-C++运算符重载->加号运算符重载、左移运算符重载、递增运算符重载、赋值运算符重载、关系运算符重载、函数调用运算符重载

#include<iostream> using namespace std; //加号运算符重载 class Person { public: Person() {}; Person(int a, int b) { this->m_A a; this->m_B b; } //1.成员函数实现 号运算符重载 Person operator(const Per…

数据结构-双指针法

介绍 双指针法是一种可以在O&#xff08;n&#xff09;时间复杂度内解决数组、链表、字符串等数据结构相关的问题的方法。核心思想为使用两个指针在不同位置遍历数组或链表&#xff0c;从而实现特定操作。 常见的双指针法有 1.快慢指针&#xff1a;快指针每次移动两步&…

【开源】基于JAVA+Vue+SpringBoot的房屋出售出租系统

目录 一、摘要1.1 项目介绍1.2 项目录屏 二、功能模块2.1 房屋销售模块2.2 房屋出租模块2.3 预定意向模块2.4 交易订单模块 三、系统展示四、核心代码4.1 查询房屋求租单4.2 查询卖家的房屋求购单4.3 出租意向预定4.4 出租单支付4.5 查询买家房屋销售交易单 五、免责说明 一、摘…

力扣精选算法100道——矩阵区域和 (前缀和专题)

目录 &#x1f388;了解题意 &#x1f388;算法原理 &#x1f388;实现代码 &#x1f388;了解题意 给定一个大小为 m x n 的矩阵 mat 和一个整数 k&#xff0c;你需要计算一个新的矩阵 answer&#xff0c;其中每个 answer[i][j] 表示矩阵 mat 中以坐标 (i, j) 为中心、边…

springboot188基于spring boot的校园商铺管理系统

简介 【毕设源码推荐 javaweb 项目】基于springbootvue 的 适用于计算机类毕业设计&#xff0c;课程设计参考与学习用途。仅供学习参考&#xff0c; 不得用于商业或者非法用途&#xff0c;否则&#xff0c;一切后果请用户自负。 看运行截图看 第五章 第四章 获取资料方式 **项…

WordPress站点如何实现发布文章即主动推送到百度快速收录和普通收录?

我们在WordPress后台成功发布文章之后&#xff0c;如果靠搜索引擎来抓取的话&#xff0c;可能会比较慢&#xff0c;所以十分有必要将我们成功发布的文章马上提交到百度、必应等搜索引擎中。下面boke112百科就跟大家说一说WordPress站点如何实现发布文章即主动推送到百度快速收录…

【自然语言处理】:实验1布置,Word2VecTranE的实现

清华大学驭风计划 因为篇幅原因实验答案分开上传&#xff0c;答案链接http://t.csdnimg.cn/5cyMG 如果需要详细的实验报告或者代码可以私聊博主 有任何疑问或者问题&#xff0c;也欢迎私信博主&#xff0c;大家可以相互讨论交流哟~~ 实验1&#xff1a; Word2Vec&TranE的…
推荐文章