首页 AI科技文章正文

🍀【总结】使用 TS 封装几条开发过程中常使用的工具函数

AI科技 2025年10月31日 00:56 0 aa

一、图片篇

场景:在前端开发过程中,经常会遇到加载静态资源(图片)时,出现加载失败。

原因:大部分是因为路径问题

  • css 使用静态资源
<template><div class="avatar"></div></template> #技术分享<script lang="ts" setup></script><style lang="less" scoped>.avatar { width: 80px; height: 80px; background-repeat: no-repeat; background-size: contain; background-position: center; background-image: url('@/assets/img/avatar.png'); } </style>

上述代码是能够正确加载图片的。


  • html 使用静态资源
<template><t-image src="@/assets/img/avatar.png"></t-image></template>

上述代码是不能够正确加载图片的。


  • 以前我的解决方法如下:
<template><t-image :src="avatarImg"></t-image></template><script lang="Ts" setup>import avatarImg from '@/assets/img/avatar.png'; </script>

先把图片在 JavaScript 中加载到变量中,在通过变量设置到 html 中。

但这种方法的缺点在于:一 个页面的静态资源图片少的话,问题不大。一旦很多,就需要设置很多变量,不方便维护。

  • 新的解决方法如下:

问题关键在于:图片路径不正确,那是否可以封装个方法做好路径的转换不就解决问题了吗

import { APP } from 'vue';const getImgSrc = (imagePath: string) => { return new URL(`../${imagePath}`, import.meta.url).href; };export const globalFunc = { install: (app: App) => { app.config.globalProperties.$getImgSrc = getImgSrc; } }

关键点:

  • import.meta.url :是拿取当前程序运行的路径,就 getImgSrc 方法,拿取的路径就是 http://www.demo.com/src/globalFunc/index.ts
  • 通过 new URL(../${imagePath}, import.meta.url).href 处理生成 http://www.demo.com/src/assets/img/avatar.png

使用:

<template><t-image :src="$getImgSrc('@/assets/img/avatar.png')"></t-image></template>

二、魔法常量篇

常量也是在前端开发中也是经常会遇到的,需要将魔法变量转化成对应的意思。

参照上一个方法的封装原则,这里也是封装成一个全局函数,比较简单,直接看代码。

import { APP } from 'vue';const translate = (values: string, type: string) => { if (!values) { return ''; } const constant = constantLabelMap[type];const valKeys = values.split(',');const valuesText: Array<string> = []; valKeys.forEach((index) => { if (constant[index]) { valuesText.push(t(constant[index])); } }); return valuesText.length > 0 ? valuesText.join(',') : values; };export const globalFunc = { install: (app: App) => { app.config.globalProperties.$constant = translate; } }

关键点:

  • 将所有常量定义到一个变量 constantLabelMap 中,通过 type 来区分不同类型的魔法常量
  • constantLabelMap 的实现,可以查看

《使用TypeScript 基于 TDesign二次封装常量组件 》 该文章实现了自动化读取魔法常量文件。

使用:

<template><div>{{ $constant('success', 'status') }}</div></template>

三、数值篇

这里主要是处理数值千分位划分,比较简单,贴代码

import { APP } from 'vue';const nf = (val: number, max?: number, min?: number, rate?: number) => { let value = val; if (rate) { value = val / rate; } const formatter = new Intl.NumberFormat('en-US', { minimumFractionDigits: min, maximumFractionDigits: max, }); return formatter.format(value); };export const globalFunc = { install: (app: App) => { app.config.globalProperties.$nf = nf; } }

关键点:

  • new Intl.NumberFormat 的使用,可以查看 MDN

四、其他工具篇

封装个指令实现复制内容到剪切板上

简简单单实现关键字高亮匹配指令

简简单单使用 TS 封装个工具库【更新中 ✍】

简简单单结合 hooks 优雅使用弹窗

实际开发中没想到 computed 在表单中还能这么使用

发表评论

长征号 Copyright © 2013-2024 长征号. All Rights Reserved.  sitemap