通用方法
1. 概述
梵医云前端项目提供了一套完整的通用方法库,涵盖了字符串处理、日期格式化、数据验证、权限校验、文件下载、DOM操作、类型判断、字典管理、路由处理、树结构处理等多个方面的工具函数。
1.1 工具方法特点
- 功能全面:涵盖前端开发的各个方面
- 类型安全:完整的 TypeScript 类型定义
- 易于使用:简洁的 API 设计
- 性能优化:针对性能敏感场景进行了优化
- 可维护性:清晰的分类和命名规范
1.2 工具方法分类
| 分类 | 说明 | 路径 |
|---|---|---|
| 通用工具 | 字符串处理、数字计算、格式化等 | @/utils/index.ts |
| 常用方法 | 日期、随机字符串、文件大小等 | @/utils/common.ts |
| 验证规则 | 表单验证规则 | @/utils/validate.ts |
| 格式化方法 | 数据格式化 | @/utils/formatter.ts |
| 日期工具 | 日期处理 | @/utils/dateUtil.ts |
| 认证相关 | Token、登录表单等 | @/utils/auth.ts |
| 权限相关 | 权限校验 | @/utils/permission.ts |
| 下载相关 | 文件下载 | @/utils/download.ts |
| DOM工具 | DOM操作 | @/utils/domUtils.ts |
| 类型判断 | 类型判断 | @/utils/is.ts |
| 字典工具 | 字典数据管理 | @/utils/dict.ts |
| 路由工具 | 路由处理 | @/utils/routerHelper.ts |
| 树工具 | 树结构处理 | @/utils/tree.ts |
2. 通用工具方法
2.1 组件注册
withInstall
为组件添加 install 方法,支持 Vue 插件注册。
import { withInstall } from '@/utils'
const MyComponent = {
name: 'MyComponent',
// ...
}
export default withInstall(MyComponent)2.2 字符串转换
humpToUnderline
将驼峰字符串转换为下划线字符串。
import { humpToUnderline } from '@/utils'
const result = humpToUnderline('userName') // 'user_name'underlineToHump
将下划线字符串转换为驼峰字符串。
import { underlineToHump } from '@/utils'
const result = underlineToHump('user_name') // 'userName'humpToDash
将驼峰字符串转换为横杠字符串。
import { humpToDash } from '@/utils'
const result = humpToDash('userName') // 'user-name'2.3 时间格式化
formatTime
格式化时间为指定格式。
import { formatTime } from '@/utils'
const result = formatTime(new Date(), 'yyyy-MM-dd HH:mm:ss')
// '2024-01-01 12:00:00'2.4 随机字符串
toAnyString
生成随机字符串。
import { toAnyString } from '@/utils'
const result = toAnyString() // 'xxxxx-xxxxx-4xxxx-yxxxx-xxxxx'generateRandomString
生成指定长度的随机字符串。
import { generateRandomString } from '@/utils/common'
const result = generateRandomString(10) // 'aB3dE5fG7h'2.5 UUID生成
generateUUID
生成 UUID。
import { generateUUID } from '@/utils'
const result = generateUUID() // '550e8400-e29b-41d4-a716-446655440000'2.6 文件大小格式化
fileSizeFormatter
格式化文件大小。
import { fileSizeFormatter } from '@/utils'
const result = fileSizeFormatter(null, null, 1024 * 1024)
// '1.00 MB'formatFileSize
格式化文件大小。
import { formatFileSize } from '@/utils/common'
const result = formatFileSize(1024 * 1024) // '1.00 MB'2.7 金额处理
formatToFraction
将整数转换为分数保留两位小数。
import { formatToFraction } from '@/utils'
const result = formatToFraction(10000) // '100.00'floatToFixed2
将数字格式化为两位小数。
import { floatToFixed2 } from '@/utils'
const result = floatToFixed2(100) // '100.00'convertToInteger
将分数转换为整数。
import { convertToInteger } from '@/utils'
const result = convertToInteger('100.00') // 10000yuanToFen
元转分。
import { yuanToFen } from '@/utils'
const result = yuanToFen('100.00') // 10000fenToYuan
分转元。
import { fenToYuan } from '@/utils'
const result = fenToYuan(10000) // '100.00'calculateRelativeRate
计算环比。
import { calculateRelativeRate } from '@/utils'
const result = calculateRelativeRate(120, 100) // '20'2.8 数组操作
getSumValue
数组求和。
import { getSumValue } from '@/utils'
const result = getSumValue([1, 2, 3, 4, 5]) // 15updateArrayWithAnother
更新数组数据。
import { updateArrayWithAnother } from '@/utils'
const arr1 = [{ id: 1, name: '张三' }]
const arr2 = [{ id: 1, name: '李四' }]
const result = updateArrayWithAnother(arr1, arr2, 'id')
// [{ id: 1, name: '李四' }]2.9 URL处理
getUrlValue
获取链接的参数值。
import { getUrlValue } from '@/utils'
const result = getUrlValue('id', 'https://example.com?id=123')
// '123'getUrlNumberValue
获取链接的参数值(数字类型)。
import { getUrlNumberValue } from '@/utils'
const result = getUrlNumberValue('id', 'https://example.com?id=123')
// 1232.10 对象操作
copyValueToTarget
将值复制到目标对象。
import { copyValueToTarget } from '@/utils'
const target = { a: 1, b: 2 }
const source = { a: 10, b: 20, c: 30 }
copyValueToTarget(target, source)
// target: { a: 10, b: 20 }flatObject
处理商品信息,扁平化对象。
import { flatObject } from '@/utils'
const obj = { name: '商品', info: { price: 100, count: 10 } }
flatObject(obj, 'info')
// { name: '商品', iPrice: 100, iCount: 10 }2.11 JSON处理
jsonParse
解析 JSON 字符串。
import { jsonParse } from '@/utils'
const result = jsonParse('{"name":"张三"}') // { name: '张三' }2.12 ERP专属方法
erpCountInputFormatter
ERP 格式化数量,保留三位小数。
import { erpCountInputFormatter } from '@/utils'
const result = erpCountInputFormatter(100.1234) // '100.123'erpPriceInputFormatter
ERP 格式化金额,保留二位小数。
import { erpPriceInputFormatter } from '@/utils'
const result = erpPriceInputFormatter(100.123) // '100.12'erpPriceMultiply
ERP 价格计算,四舍五入保留两位小数。
import { erpPriceMultiply } from '@/utils'
const result = erpPriceMultiply(10.5, 2) // 21.00erpCalculatePercentage
ERP 百分比计算,四舍五入保留两位小数。
import { erpCalculatePercentage } from '@/utils'
const result = erpCalculatePercentage(25, 100) // '25.00'erpToFixed2
ERP 分转为元,四舍五入保留两位小数。
import { erpToFixed2 } from '@/utils'
const result = erpToFixed2(10000) // '100.00'3. 常用方法
3.1 获取当前时间
getFormatDate
获取当前时间,格式为 yyyy-MM-dd HH:mm:ss。
import { getFormatDate } from '@/utils/common'
const result = getFormatDate() // '2024-01-01 12:00:00'3.2 日期工具
formatToDateTime
格式化日期时间。
import { formatToDateTime } from '@/utils/dateUtil'
const result = formatToDateTime(new Date()) // '2024-01-01 12:00:00'formatToDate
格式化日期。
import { formatToDate } from '@/utils/dateUtil'
const result = formatToDate(new Date()) // '2024-01-01'dateUtil
dayjs 实例。
import { dateUtil } from '@/utils/dateUtil'
const result = dateUtil().format('YYYY-MM-DD') // '2024-01-01'4. 验证规则
4.1 手机号验证
isPhone
判断是否是手机号。
import { isPhone } from '@/utils/validate'
const result = isPhone('13800138000') // truevalidatePhone
电话号码验证。
import { validatePhone } from '@/utils/validate'
const rule = { phonetype: 'mobile' }
validatePhone(rule, '13800138000', (error) => {
if (error) {
console.log(error.message)
}
})4.2 身份证验证
isIdCard
判断是否是身份证号。
import { isIdCard } from '@/utils/validate'
const result = isIdCard('110101199003078034') // truevalidateIdCard
身份证验证函数。
import { validateIdCard } from '@/utils/validate'
const result = validateIdCard('110101199003078034') // true4.3 邮箱验证
validateEmail
邮箱验证。
import { validateEmail } from '@/utils/validate'
validateEmail({}, 'test@example.com', (error) => {
if (error) {
console.log(error.message)
}
})4.4 字符验证
isLowerCase
判断是否是小写字母。
import { isLowerCase } from '@/utils/validate'
const result = isLowerCase('abc') // trueisUpperCase
判断是否是大写字母。
import { isUpperCase } from '@/utils/validate'
const result = isUpperCase('ABC') // trueisAlphabets
判断是否是大写字母开头。
import { isAlphabets } from '@/utils/validate'
const result = isAlphabets('Abc') // truevalidateIntOrLet
只允许输入数字或字母。
import { validateIntOrLet } from '@/utils/validate'
validateIntOrLet({}, 'abc123', (error) => {
if (error) {
console.log(error.message)
}
})validateInt
只允许输入数字。
import { validateInt } from '@/utils/validate'
validateInt({}, '123', (error) => {
if (error) {
console.log(error.message)
}
})validateIntNumber
只允许输入正整数。
import { validateIntNumber } from '@/utils/validate'
validateIntNumber({}, '123', (error) => {
if (error) {
console.log(error.message)
}
})4.5 经纬度验证
isLongitude
判断经度 -180.0~+180.0。
import { isLongitude } from '@/utils/validate'
const result = isLongitude('116.404') // trueisLatitude
判断纬度 -90.0~+90.0。
import { isLatitude } from '@/utils/validate'
const result = isLatitude('39.915') // true4.6 日期验证
gtNowDate
大于当前日期。
import { gtNowDate } from '@/utils/validate'
gtNowDate({}, '2025-01-01', (error) => {
if (error) {
console.log(error.message)
}
})ltNowDate
小于当前日期。
import { ltNowDate } from '@/utils/validate'
ltNowDate({}, '2023-01-01', (error) => {
if (error) {
console.log(error.message)
}
})5. 格式化方法
5.1 金额格式化
fenToYuanFormat
格式化金额(分转元),带¥符号。
import { fenToYuanFormat } from '@/utils/formatter'
const result = fenToYuanFormat(null, null, 10000, null) // '¥100.00'fenToDouFormat
格式化金额(分转元)。
import { fenToDouFormat } from '@/utils/formatter'
const result = fenToDouFormat(null, null, 10000, null) // '100.00'5.2 隐私处理
maskPhoneNumber
处理手机号加星。
import { maskPhoneNumber } from '@/utils/formatter'
const result = maskPhoneNumber(null, null, '13800138000', null)
// '138****8000'idCardFormat
处理身份证号星。
import { idCardFormat } from '@/utils/formatter'
const result = idCardFormat(null, null, '110101199003078034', null)
// '110*************8034'6. 认证相关
6.1 Token管理
getAccessToken
获取访问令牌。
import { getAccessToken } from '@/utils/auth'
const token = getAccessToken()getRefreshToken
获取刷新令牌。
import { getRefreshToken } from '@/utils/auth'
const refreshToken = getRefreshToken()setToken
设置令牌。
import { setToken } from '@/utils/auth'
setToken({
accessToken: 'xxx',
refreshToken: 'yyy'
})removeToken
删除令牌。
import { removeToken } from '@/utils/auth'
removeToken()formatToken
格式化令牌(JWT格式)。
import { formatToken } from '@/utils/auth'
const token = formatToken('xxx') // 'Bearer xxx'6.2 登录表单
getLoginForm
获取登录表单。
import { getLoginForm } from '@/utils/auth'
const loginForm = getLoginForm()setLoginForm
设置登录表单。
import { setLoginForm } from '@/utils/auth'
setLoginForm({
tenantName: 'tenant',
username: 'admin',
password: '123456',
rememberMe: true
})removeLoginForm
删除登录表单。
import { removeLoginForm } from '@/utils/auth'
removeLoginForm()6.3 租户管理
getTenantId
获取租户ID。
import { getTenantId } from '@/utils/auth'
const tenantId = getTenantId()setTenantId
设置租户ID。
import { setTenantId } from '@/utils/auth'
setTenantId('1')7. 权限相关
7.1 字符权限校验
checkPermi
字符权限校验。
import { checkPermi } from '@/utils/permission'
const hasPermission = checkPermi(['system:user:add'])7.2 角色权限校验
checkRole
角色权限校验。
import { checkRole } from '@/utils/permission'
const hasRole = checkRole(['admin'])8. 下载相关
8.1 Excel下载
download.excel
下载 Excel 文件。
import download from '@/utils/download'
const blob = new Blob([data], { type: 'application/vnd.ms-excel' })
download.excel(blob, 'data.xlsx')8.2 Word下载
download.word
下载 Word 文件。
import download from '@/utils/download'
const blob = new Blob([data], { type: 'application/msword' })
download.word(blob, 'data.docx')8.3 Zip下载
download.zip
下载 Zip 文件。
import download from '@/utils/download'
const blob = new Blob([data], { type: 'application/zip' })
download.zip(blob, 'data.zip')8.4 图片下载
download.image
下载图片。
import download from '@/utils/download'
download.image({
url: 'https://example.com/image.png',
canvasWidth: 800,
canvasHeight: 600
})9. DOM工具
9.1 Class操作
hasClass
判断元素是否有指定class。
import { hasClass } from '@/utils/domUtils'
const hasClass = hasClass(element, 'active')addClass
为元素添加class。
import { addClass } from '@/utils/domUtils'
addClass(element, 'active')removeClass
移除元素的class。
import { removeClass } from '@/utils/domUtils'
removeClass(element, 'active')9.2 样式操作
getStyle
获取元素的样式。
import { getStyle } from '@/utils/domUtils'
const color = getStyle(element, 'color')setStyle
设置元素的样式。
import { setStyle } from '@/utils/domUtils'
setStyle(element, 'color', 'red')9.3 事件操作
on
添加事件监听。
import { on } from '@/utils/domUtils'
on(element, 'click', handler)off
移除事件监听。
import { off } from '@/utils/domUtils'
off(element, 'click', handler)once
添加一次性事件监听。
import { once } from '@/utils/domUtils'
once(element, 'click', handler)9.4 元素位置
getBoundingClientRect
获取元素的位置信息。
import { getBoundingClientRect } from '@/utils/domUtils'
const rect = getBoundingClientRect(element)getViewportOffset
获取元素的偏移信息。
import { getViewportOffset } from '@/utils/domUtils'
const offset = getViewportOffset(element)9.5 滚动容器
isScroll
判断元素是否可滚动。
import { isScroll } from '@/utils/domUtils'
const canScroll = isScroll(element, true)getScrollContainer
获取滚动容器。
import { getScrollContainer } from '@/utils/domUtils'
const container = getScrollContainer(element)isInContainer
判断元素是否在容器内。
import { isInContainer } from '@/utils/domUtils'
const inContainer = isInContainer(element, container)10. 类型判断
10.1 基础类型判断
is
类型判断。
import { is } from '@/utils/is'
const result = is('hello', 'String') // trueisDef
判断是否已定义。
import { isDef } from '@/utils/is'
const result = isDef('hello') // trueisUnDef
判断是否未定义。
import { isUnDef } from '@/utils/is'
const result = isUnDef(undefined) // trueisObject
判断是否是对象。
import { isObject } from '@/utils/is'
const result = isObject({}) // trueisEmpty
判断是否为空。
import { isEmpty } from '@/utils/is'
const result = isEmpty([]) // trueisNull
判断是否为null。
import { isNull } from '@/utils/is'
const result = isNull(null) // trueisNumber
判断是否是数字。
import { isNumber } from '@/utils/is'
const result = isNumber(123) // trueisString
判断是否是字符串。
import { isString } from '@/utils/is'
const result = isString('hello') // trueisFunction
判断是否是函数。
import { isFunction } from '@/utils/is'
const result = isFunction(() => {}) // trueisBoolean
判断是否是布尔值。
import { isBoolean } from '@/utils/is'
const result = isBoolean(true) // trueisArray
判断是否是数组。
import { isArray } from '@/utils/is'
const result = isArray([1, 2, 3]) // true10.2 特殊类型判断
isDate
判断是否是日期。
import { isDate } from '@/utils/is'
const result = isDate(new Date()) // trueisPromise
判断是否是Promise。
import { isPromise } from '@/utils/is'
const result = isPromise(Promise.resolve()) // trueisRegExp
判断是否是正则表达式。
import { isRegExp } from '@/utils/is'
const result = isRegExp(/test/) // trueisMap
判断是否是Map。
import { isMap } from '@/utils/is'
const result = isMap(new Map()) // true10.3 环境判断
isServer
判断是否是服务端。
import { isServer } from '@/utils/is'
const result = isServer() // falseisClient
判断是否是客户端。
import { isClient } from '@/utils/is'
const result = isClient() // true10.4 URL判断
isUrl
判断是否是URL。
import { isUrl } from '@/utils/is'
const result = isUrl('https://example.com') // trueisImgPath
判断是否是图片路径。
import { isImgPath } from '@/utils/is'
const result = isImgPath('https://example.com/image.png') // true10.5 浏览器判断
isChrome
判断是否是Chrome浏览器。
import { isChrome } from '@/utils/is'
const result = isChrome() // trueisFirefox
判断是否是Firefox浏览器。
import { isFirefox } from '@/utils/is'
const result = isFirefox() // falseisSafari
判断是否是Safari浏览器。
import { isSafari } from '@/utils/is'
const result = isSafari() // falseisEdge
判断是否是Edge浏览器。
import { isEdge } from '@/utils/is'
const result = isEdge() // falseisIE
判断是否是IE浏览器。
import { isIE } from '@/utils/is'
const result = isIE() // false10.6 设备判断
isIOS
判断是否是iOS。
import { isIOS } from '@/utils/is'
const result = isIOS() // falseisAndroid
判断是否是Android。
import { isAndroid } from '@/utils/is'
const result = isAndroid() // falseisMobile
判断是否是移动端。
import { isMobile } from '@/utils/is'
const result = isMobile() // falseisPC
判断是否是PC。
import { isPC } from '@/utils/is'
const result = isPC() // true11. 字典工具
11.1 获取字典选项
getDictOptions
获取指定字典类型的数据字典数组。
import { getDictOptions } from '@/utils/dict'
const options = getDictOptions('common_status')getIntDictOptions
获取整数类型的字典选项。
import { getIntDictOptions } from '@/utils/dict'
const options = getIntDictOptions('common_status')getStrDictOptions
获取字符串类型的字典选项。
import { getStrDictOptions } from '@/utils/dict'
const options = getStrDictOptions('common_status')getBoolDictOptions
获取布尔类型的字典选项。
import { getBoolDictOptions } from '@/utils/dict'
const options = getBoolDictOptions('common_status')11.2 获取字典数据
getDictObj
获取指定字典类型的指定值对应的字典对象。
import { getDictObj } from '@/utils/dict'
const dict = getDictObj('common_status', 0)getDictLabel
获得字典数据的文本展示。
import { getDictLabel } from '@/utils/dict'
const label = getDictLabel('common_status', 0)11.3 字典类型枚举
DICT_TYPE
字典类型枚举。
import { DICT_TYPE } from '@/utils/dict'
// 用户类型
DICT_TYPE.USER_TYPE
// 通用状态
DICT_TYPE.COMMON_STATUS
// 商品状态
DICT_TYPE.PRODUCT_SPU_STATUS
// 订单状态
DICT_TYPE.TRADE_ORDER_STATUS
// ... 更多字典类型12. 路由工具
12.1 组件注册
registerComponent
注册一个异步组件。
import { registerComponent } from '@/utils/routerHelper'
const component = registerComponent('/bpm/oa/leave/detail')12.2 路由排序
ascending
按照路由中meta下的rank等级升序来排序路由。
import { ascending } from '@/utils/routerHelper'
const sortedRoutes = ascending(routes)12.3 路由生成
generateRoute
后端控制路由生成。
import { generateRoute } from '@/utils/routerHelper'
const routes = generateRoute(backendRoutes)12.4 路径处理
pathResolve
路径解析。
import { pathResolve } from '@/utils/routerHelper'
const path = pathResolve('/parent', '/child') // '/parent/child'12.5 路由降级
flatMultiLevelRoutes
路由降级。
import { flatMultiLevelRoutes } from '@/utils/routerHelper'
const flatRoutes = flatMultiLevelRoutes(routes)13. 树工具
13.1 列表与树转换
listToTree
列表转树。
import { listToTree } from '@/utils/tree'
const tree = listToTree(list)treeToList
树转列表。
import { treeToList } from '@/utils/tree'
const list = treeToList(tree)13.2 查找节点
findNode
查找节点。
import { findNode } from '@/utils/tree'
const node = findNode(tree, (node) => node.id === 1)findNodeAll
查找所有节点。
import { findNodeAll } from '@/utils/tree'
const nodes = findNodeAll(tree, (node) => node.type === 'folder')13.3 查找路径
findPath
查找路径。
import { findPath } from '@/utils/tree'
const path = findPath(tree, (node) => node.id === 1)findPathAll
查找所有路径。
import { findPathAll } from '@/utils/tree'
const paths = findPathAll(tree, (node) => node.type === 'folder')13.4 过滤和遍历
filter
过滤树。
import { filter } from '@/utils/tree'
const filteredTree = filter(tree, (node) => node.status === 1)forEach
遍历树。
import { forEach } from '@/utils/tree'
forEach(tree, (node) => {
console.log(node)
})eachTree
递归遍历树结构。
import { eachTree } from '@/utils/tree'
eachTree(tree, (node, parentNode) => {
console.log(node, parentNode)
})13.5 树映射
treeMap
提取树指定结构。
import { treeMap } from '@/utils/tree'
const mappedTree = treeMap(treeData, {
children: 'children',
conversion: (node) => ({
id: node.id,
name: node.name
})
})13.6 构造树结构
handleTree
构造树型结构数据。
import { handleTree } from '@/utils/tree'
const tree = handleTree(data, 'id', 'parentId', 'children')handleTree2
构造树型结构数据。
import { handleTree2 } from '@/utils/tree'
const tree = handleTree2(data, 'id', 'parentId', 'children', 0)13.7 树校验
checkSelectedNode
校验选中的节点,是否为指定level。
import { checkSelectedNode } from '@/utils/tree'
const isLevel2 = checkSelectedNode(tree, nodeId, 2)13.8 树转字符串
treeToString
获取节点的完整结构。
import { treeToString } from '@/utils/tree'
const str = treeToString(tree, nodeId)14. 最佳实践
14.1 按需导入
推荐按需导入工具函数。
// 好的做法
import { formatTime, isPhone, getDictOptions } from '@/utils'
// 不好的做法
import * as Utils from '@/utils'14.2 类型安全
使用 TypeScript 类型定义。
import { DictDataType } from '@/utils/dict'
const options: DictDataType[] = getDictOptions('common_status')14.3 错误处理
对可能出错的操作进行错误处理。
import { jsonParse } from '@/utils'
try {
const data = jsonParse(jsonString)
} catch (error) {
console.error('JSON解析失败', error)
}14.4 性能优化
避免在循环中重复计算。
// 好的做法
const format = (value) => formatTime(value, 'yyyy-MM-dd')
const formattedDates = dates.map(format)
// 不好的做法
const formattedDates = dates.map(date => formatTime(date, 'yyyy-MM-dd'))15. 常见问题
15.1 字典数据为空
问题原因:
- 字典类型不正确
- 字典数据未加载
解决方案:
import { getDictOptions } from '@/utils/dict'
const options = getDictOptions('common_status')
if (options.length === 0) {
console.warn('字典数据为空')
}15.2 Token过期
问题原因:
- Token已过期
- 未正确刷新Token
解决方案:
import { getAccessToken, removeToken } from '@/utils/auth'
const token = getAccessToken()
if (!token) {
removeToken()
// 跳转到登录页
}15.3 权限校验失败
问题原因:
- 权限字符串不正确
- 用户无对应权限
解决方案:
import { checkPermi } from '@/utils/permission'
if (checkPermi(['system:user:add'])) {
// 有权限
} else {
// 无权限
}注意:本文档持续更新中,如有问题请及时反馈。
