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

这篇具有很好参考价值的文章主要介绍了前端新手Vue3+Vite+Ts+Pinia+Sass项目指北系列文章 —— 第十二章 常用工具函数 (Utils配置)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

前言

在项目开发中,我们经常会使用一些工具函数,也经常会用到例如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')
    return

  document.onkeydown = (e) => {
    const ev: KeyboardEventInit = e || window.event
    const keyCode = ev.code || ev.keyCode
    if (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 null

  const format = pattern || '{y}-{m}-{d}'
  let date
  if (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 * 1000

    date = 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})+(?:$|\.))/g
  num = 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 = value
  document.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 = null
  return (...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 = href
  downloadElement.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()
  },
}

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

总结

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

写在最后

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

到了这里,关于前端新手Vue3+Vite+Ts+Pinia+Sass项目指北系列文章 —— 第十二章 常用工具函数 (Utils配置)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Vue3+TS+Vite创建项目,并导入Element-plus和Sass

    1.桌面新建一个文件夹Vue3-app 打开编辑器导入文件夹,编辑器打开终端输入或者命令行工具cd到项目目录下输入 npm init vue@latest 回车运行 这里我选择了TS+Vite来开发,并选择安装路由 2.cd到 vue-project目录下 输入 npm install 回车运行 3.安装完成后 输入 npm run dev 回车运行 浏览器打开

    2024年02月16日
    浏览(50)
  • vite + vue3 + vue-router4 + ts + element plus + pinia + axios构建项目

    最后是完整的vite.config.ts、main.ts配置 1、先用vite创建一个项目 2、安装element plus vite.config.ts配置组件按需导入,图标自动导入   main.ts配置 页面文件使用 3、安装axios main.ts 4、安装pinia /stores/index.ts /stores/counter.ts main.ts 页面使用 5、安装router4 /router/index main.ts   6、vite.config.ts常

    2023年04月25日
    浏览(42)
  • 从0开始搭建一个vue3+vite+ts+pinia+element-plus的项目

    前言:vue3+ts+vite大家已经都开始用了,最近也在学习,基本上是零基础开始ts的学习,很多语法知识是边写边查,没有系统的学习ts。此处展示从零开始,搭建的一个框架,方便拿来即用! 其中框架选择vue,语言选择typeScript 项目启动成功以后如下所示: 为了方便日常工作中

    2024年02月06日
    浏览(55)
  • 【Vue H5项目实战】从0到1的自助点餐系统—— 搭建脚手架(Vue3.2 + Vite + TS + Vant + Pinia + Node.js)

    H5 项目基于 Web 技术,可以在智能手机、平板电脑等移动设备上的浏览器中运行,无需下载和安装任何应用程序,且H5 项目的代码和资源可以集中在服务器端进行管理,只需更新服务器上的代码,即可让所有顾客访问到最新的系统版本。 本系列将以肯德基自助点餐页面为模板

    2024年02月13日
    浏览(49)
  • vue3+ts+pinia+vite一次性全搞懂

    前提是所处vue环境为vue3,如果失败就查看一下环境是否为vue2,然后删除vue2,安装vue3 这是我报过的错

    2024年02月01日
    浏览(35)
  • Vite4+Typescript+Vue3+Pinia 从零搭建(2) - ts配置

    项目代码同步至码云 weiz-vue3-template 关于tsconfig的配置字段可查看其他文档,如 typeScript tsconfig配置详解 文件修改如下: 修改文件如下: 新建文件夹 types ,用来存放类型定义。比如新建 index.d.ts : 后续也可以新增其他文件,比如 global.d.ts 存放全局定义, router.d.ts 存放路由定

    2024年02月05日
    浏览(67)
  • Vue3 Vite4 ElementPlus TS模板(含Vue-Router4+Pinia4)

    手动安装配置Vue3 ElementPlus模板比较繁琐,网上寻找一些模板不太符合自己预期,因此花点精力搭建一个符合自己需求的架子 采用最新的组件,版本如下: vite 4.3.9 vite-plugin-mock 2.9.8 vue 3.3.4 pinia 2.1.3 vue-router 4.2.2 element-plus 2.3.6 满足自己以下功能: Vite工具热启动速度快,修改后

    2024年02月08日
    浏览(46)
  • 前端开发小技巧 - 【Vue3 + TS】 - 在 TS + Vue3 中使用 Pinia,实现 Pinia 的持久化,优化Pinia(仓库统一管理)

    ts 中使用 pinia 和 Vue3 基本一致,唯一的不同点在于,需要根据接口文档给 state 标注类型,也要给 actions 标注类型; 以下都是 组合式API 的写法, 选项式API 的写法大家可以去官网看看; Pinia; 持久化插件 - pinia-plugin-persistedstate; 目标文件: src/types/user.d.ts (这里以 user.d.t

    2024年04月09日
    浏览(45)
  • Vue3.2 + TypeScript + Pinia + Vite4 + Element-Plus + 微前端(qiankun) 后台管理系统模板(已开源---显示项目页面截图)

    Wocwin-Admin,是基于 Vue3.2、TypeScript、Vite、Pinia、Element-Plus、Qiankun(微前端) 开源的一套后台管理模板;同时集成了微前端 qiankun也可以当做一个子应用。项目中组件页面使用了Element-plus 二次封装 t-ui-plus 组件,目前已新增fastmock接口。 Link:https://wocwin.github.io/wocwin-admin/ 账号:

    2024年02月08日
    浏览(73)
  • Vite-Admin后台管理系统|vite4+vue3+pinia前端后台框架实例

    基于 vite4.x+vue3+pinia 前端后台管理系统解决方案 ViteAdmin 。 前段时间分享了一篇vue3自研pc端UI组件库VEPlus。这次带来最新开发的基于 vite4+vue3+pinia 技术栈搭配ve-plus组件库构建的中后台权限管理系统框架。 支持vue-i18n国际化多语言、动态路由鉴权、4种布局模板及tab页面缓存 等功

    2023年04月13日
    浏览(72)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包