Files
easygoadmin-wiki/EasyGoAdmin_GoFrame_NaiveVue/zh/frontend/utils.md
T
2026-10-20 21:53:26 +08:00

75 lines
2.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 9.16 工具函数
:::tip 概述
utils/ 提供通用工具:HTTP 封装(9.4 已述)、Storage 本地存储、auth 路径工具、downloadFile 下载、dateUtil/formatTime 时间、validate 校验、is 类型判断、urlUtils 等。本节速查常用函数。
:::
## utils/ 工具地图
| 文件/目录 | 职责 | 常用函数 |
|-----------|------|---------|
| http/axios | HTTP 封装 | http.request(详见 9.4) |
| Storage.ts | 本地存储封装 | storage.get/set/remove(token 等) |
| auth.ts | 路由/树工具 | getNormalPath、isExternal、findTreeByPath、objectToQuery |
| downloadFile.ts | 文件下载 | 导出 URL 触发浏览器下载 |
| dateUtil.ts / formatTime.ts | 日期处理 | dayjs 封装、格式化 |
| validate.ts | 校验 | 表单校验辅助 |
| urlUtils.ts | URL 工具 | setObjToUrlParams(参数拼接) |
| is/ | 类型判断 | isString/isUrl/isEmpty… |
| helper/ lib/ file/ | 辅助函数库 | 按需探索 |
| propTypes.ts | prop 类型 | 组件 prop 校验 |
| color.ts | 颜色 | 主题色处理 |
| log.ts | 日志 | 调试日志 |
| lodashChunk.ts | 分块 | 数组分块 |
| useLockFn.ts | 防重 | 函数锁(防连点) |
| wartermark.ts | 水印 | 水印绘制 |
## Storage(令牌存取核心)
```ts
import { storage } from '@/utils/Storage';
storage.get(ACCESS_TOKEN); // 守卫/拦截器读取
storage.set(ACCESS_TOKEN, v); // 登录写入
storage.remove(ACCESS_TOKEN); // 登出清除
// ACCESS_TOKEN 键名常量在 store/mutation-types.ts
```
## auth.ts 路径工具(守卫消费)
```text
isExternal(path) 是否外链(https?:/mailto:/tel:)
getNormalPath(path) 路径归一(去重复斜杠/尾斜杠)
findTreeByPath 按 path 查菜单树节点(首个可达路由定位)
objectToQuery 对象转 query 字符串
```
## 下载与时间
```ts
// 导出下载:后端返回文件 URL → 触发浏览器下载
import { downloadFile } from '@/utils/downloadFile';
downloadFile(url);
// 日期:dayjs 封装
import { formatTime } from '@/utils/dateUtil';
```
## hooks/ 配合(组合式复用)
```text
hooks/core/ 核心(useMessage 等)
hooks/setting/ useGlobSetting(读环境变量)/ useDesign(主题)
hooks/web/ useBattery/useOnline/useTime 等浏览器能力
hooks/event/ 事件
```
## 使用规约
+ 工具函数无业务依赖(不 import api/store)——保持纯函数/低耦合
+ 新增公共工具放 utils/,仅页面用的放页面目录或 hooks
+ 日期统一 dayjs(勿混用 moment/原生拼串)
+ 本地存储统一 storage 封装(不直接 localStorage——便于前缀/过期管理)
+ 类型判断用 is/ 目录(勿手写 toString 判断)