🍀【总结】使用 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 在表单中还能这么使用🚀🚀

相关推荐
骑着蜗牛撵大象32711 分钟前
豆包 Seed 驱动的记账智能体:从拍票抽取到月报生成的全链路落地记录
java·前端·javascript·结构化输出·豆包seed·多模态识别·记账系统
溪语流沙12 分钟前
【Web全栈进阶】前端世界观:现代工具链与框架为什么存在
前端·javascript·vue.js
kyriewen34 分钟前
我逐个测了 JSON.stringify 的 7 个坑:第 1 个就在丢数据
前端·javascript·程序员
积流成海1 小时前
用代码实现哈希计算器:Web Crypto API 实战
前端·算法·哈希算法·哈希函数·盘子工具站
data analyse 4561 小时前
服务端访问日志聚合 PV 与 UV 怎么实现?日志采集与口径设计
大数据·前端·数据分析
JavaGuide1 小时前
DeepSeek Harness 重磅更新,Codex、Claude Code 子智能体进官方插件列表了,还有 Git 工作树和思考翻译!
前端·后端
小羊没烦恼!1 小时前
OS X 上使用.NET开发应用程序
开发语言·前端·数据库·人工智能·c#·策略模式
Eiceblue2 小时前
使用 Python 实现 Excel 行列转置(保留单元格样式)
前端·python·excel
西西学代码3 小时前
像素和颜色之间的转换(Flutter)
前端·javascript·flutter
茶底世界之下3 小时前
羽毛颜色已经很鲜艳,还要继续加色吗?用 Awaking 试一次减饱和
前端·ios·运营