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

一、图片篇

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

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

  • css 使用静态资源
vue 复制代码
<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 使用静态资源
vue 复制代码
<template>
   <t-image src="@/assets/img/avatar.png"></t-image>
</template>

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


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

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

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

  • 新的解决方法如下:

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

typeScript 复制代码
// src/globalFunc/index.ts
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

使用:

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

二、魔法常量篇

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

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

typescript 复制代码
// src/globalFunc/index.ts
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;
  }
}

关键点:

使用:

vue 复制代码
<template>
    <div>{{ $constant('success', 'status') }}</div>
</template>

三、数值篇

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

typescript 复制代码
// src/globalFunc/index.ts
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 在表单中还能这么使用🚀🚀

相关推荐
小飞侠在吗4 小时前
vue props
前端·javascript·vue.js
DsirNg5 小时前
页面栈溢出问题修复总结
前端·微信小程序
小徐_23335 小时前
uni-app 也能远程调试?使用 PageSpy 打开调试的新大门!
前端·微信小程序·uni-app
大怪v5 小时前
【Virtual World 03】上帝之手
前端·javascript
别叫我->学废了->lol在线等7 小时前
演示 hasattr 和 ** 解包操作符
开发语言·前端·python
霍夫曼7 小时前
UTC时间与本地时间转换问题
java·linux·服务器·前端·javascript
DARLING Zero two♡8 小时前
浏览器里跑 AI 语音转写?Whisper Web + cpolar让本地服务跑遍全网
前端·人工智能·whisper
Lovely Ruby8 小时前
前端er Go-Frame 的学习笔记:实现 to-do 功能(三),用 docker 封装成镜像,并且同时启动前后端数据库服务
前端·学习·golang
深红8 小时前
玩转小程序AR-实战篇
前端·微信小程序·webvr
银空飞羽8 小时前
让Trae SOLO全自主学习开发近期爆出的React RCE漏洞靶场并自主利用验证(CVE-2025-55182)
前端·人工智能·安全