一、图片篇
场景:在前端开发过程中,经常会遇到加载静态资源(图片)时,出现加载失败。
原因:大部分是因为路径问题
- 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;
}
}
关键点:
-
将所有常量定义到一个变量
constantLabelMap中,通过type来区分不同类型的魔法常量 -
constantLabelMap的实现,可以查看# 《🍀使用TypeScript 基于 TDesign二次封装常量组件 🚀🚀》 该文章实现了自动化读取魔法常量文件。
使用:
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