初始化

This commit is contained in:
2025-07-01 21:08:51 +08:00
commit 57aa9e21ed
1649 changed files with 242230 additions and 0 deletions

100
src/utils/Logger.ts Normal file
View File

@@ -0,0 +1,100 @@
const isArray = function (obj: any): boolean {
return Object.prototype.toString.call(obj) === '[object Array]'
}
const Logger = () => {}
Logger.typeColor = function (type: string) {
let color = ''
switch (type) {
case 'primary':
color = '#2d8cf0'
break
case 'success':
color = '#19be6b'
break
case 'info':
color = '#909399'
break
case 'warn':
color = '#ff9900'
break
case 'error':
color = '#f03f14'
break
default:
color = '#35495E'
break
}
return color
}
Logger.print = function (type = 'default', text: any, back = false) {
if (typeof text === 'object') {
// 如果是對象則調用打印對象方式
isArray(text) ? console.table(text) : console.dir(text)
return
}
if (back) {
// 如果是打印帶背景圖的
console.log(
`%c ${text} `,
`background:${Logger.typeColor(type)}; padding: 2px; border-radius: 4px; color: #fff;`
)
} else {
console.log(
`%c ${text} `,
`border: 1px solid ${Logger.typeColor(type)};
padding: 2px; border-radius: 4px;
color: ${Logger.typeColor(type)};`
)
}
}
Logger.printBack = function (type = 'primary', text) {
this.print(type, text, true)
}
Logger.pretty = function (type = 'primary', title, text) {
if (typeof text === 'object') {
console.group('Console Group', title)
console.log(
`%c ${title}`,
`background:${Logger.typeColor(type)};border:1px solid ${Logger.typeColor(type)};
padding: 1px; border-radius: 4px; color: #fff;`
)
isArray(text) ? console.table(text) : console.dir(text)
console.groupEnd()
return
}
console.log(
`%c ${title} %c ${text} %c`,
`background:${Logger.typeColor(type)};border:1px solid ${Logger.typeColor(type)};
padding: 1px; border-radius: 4px 0 0 4px; color: #fff;`,
`border:1px solid ${Logger.typeColor(type)};
padding: 1px; border-radius: 0 4px 4px 0; color: ${Logger.typeColor(type)};`,
'background:transparent'
)
}
Logger.prettyPrimary = function (title, ...text) {
text.forEach((t) => this.pretty('primary', title, t))
}
Logger.prettySuccess = function (title, ...text) {
text.forEach((t) => this.pretty('success', title, t))
}
Logger.prettyWarn = function (title, ...text) {
text.forEach((t) => this.pretty('warn', title, t))
}
Logger.prettyError = function (title, ...text) {
text.forEach((t) => this.pretty('error', title, t))
}
Logger.prettyInfo = function (title, ...text) {
text.forEach((t) => this.pretty('info', title, t))
}
export default Logger

80
src/utils/auth.ts Normal file
View File

@@ -0,0 +1,80 @@
import { useCache, CACHE_KEY } from '@/hooks/web/useCache'
import { TokenType } from '@/api/login/types'
import { decrypt, encrypt } from '@/utils/jsencrypt'
const { wsCache } = useCache()
const AccessTokenKey = 'ACCESS_TOKEN'
const RefreshTokenKey = 'REFRESH_TOKEN'
// 获取token
export const getAccessToken = () => {
// 此处与TokenKey相同此写法解决初始化时Cookies中不存在TokenKey报错
const accessToken = wsCache.get(AccessTokenKey)
return accessToken ? accessToken : wsCache.get('ACCESS_TOKEN')
}
// 刷新token
export const getRefreshToken = () => {
return wsCache.get(RefreshTokenKey)
}
// 设置token
export const setToken = (token: TokenType) => {
wsCache.set(RefreshTokenKey, token.refreshToken)
wsCache.set(AccessTokenKey, token.accessToken)
}
// 删除token
export const removeToken = () => {
wsCache.delete(AccessTokenKey)
wsCache.delete(RefreshTokenKey)
}
/** 格式化tokenjwt格式 */
export const formatToken = (token: string): string => {
return 'Bearer ' + token
}
// ========== 账号相关 ==========
export type LoginFormType = {
tenantName: string
username: string
password: string
rememberMe: boolean
}
export const getLoginForm = () => {
const loginForm: LoginFormType = wsCache.get(CACHE_KEY.LoginForm)
if (loginForm) {
loginForm.password = decrypt(loginForm.password) as string
}
return loginForm
}
export const setLoginForm = (loginForm: LoginFormType) => {
loginForm.password = encrypt(loginForm.password) as string
wsCache.set(CACHE_KEY.LoginForm, loginForm, { exp: 30 * 24 * 60 * 60 })
}
export const removeLoginForm = () => {
wsCache.delete(CACHE_KEY.LoginForm)
}
// ========== 租户相关 ==========
export const getTenantId = () => {
return wsCache.get(CACHE_KEY.TenantId)
}
export const setTenantId = (tenantId: number) => {
wsCache.set(CACHE_KEY.TenantId, tenantId)
}
export const getVisitTenantId = () => {
return wsCache.get(CACHE_KEY.VisitTenantId)
}
export const setVisitTenantId = (visitTenantId: number) => {
wsCache.set(CACHE_KEY.VisitTenantId, visitTenantId)
}

217
src/utils/color.ts Normal file
View File

@@ -0,0 +1,217 @@
/**
* 判断是否 十六进制颜色值.
* 输入形式可为 #fff000 #f00
*
* @param String color 十六进制颜色值
* @return Boolean
*/
export const isHexColor = (color: string) => {
const reg = /^#([0-9a-fA-F]{3}|[0-9a-fA-f]{6})$/
return reg.test(color)
}
/**
* RGB 颜色值转换为 十六进制颜色值.
* r, g, 和 b 需要在 [0, 255] 范围内
*
* @return String 类似#ff00ff
* @param r
* @param g
* @param b
*/
export const rgbToHex = (r: number, g: number, b: number) => {
// tslint:disable-next-line:no-bitwise
const hex = ((r << 16) | (g << 8) | b).toString(16)
return '#' + new Array(Math.abs(hex.length - 7)).join('0') + hex
}
/**
* Transform a HEX color to its RGB representation
* @param {string} hex The color to transform
* @returns The RGB representation of the passed color
*/
export const hexToRGB = (hex: string, opacity?: number) => {
let sHex = hex.toLowerCase()
if (isHexColor(hex)) {
if (sHex.length === 4) {
let sColorNew = '#'
for (let i = 1; i < 4; i += 1) {
sColorNew += sHex.slice(i, i + 1).concat(sHex.slice(i, i + 1))
}
sHex = sColorNew
}
const sColorChange: number[] = []
for (let i = 1; i < 7; i += 2) {
sColorChange.push(parseInt('0x' + sHex.slice(i, i + 2)))
}
return opacity
? 'RGBA(' + sColorChange.join(',') + ',' + opacity + ')'
: 'RGB(' + sColorChange.join(',') + ')'
}
return sHex
}
export const colorIsDark = (color: string) => {
if (!isHexColor(color)) return
const [r, g, b] = hexToRGB(color)
.replace(/(?:\(|\)|rgb|RGB)*/g, '')
.split(',')
.map((item) => Number(item))
return r * 0.299 + g * 0.578 + b * 0.114 < 192
}
/**
* Darkens a HEX color given the passed percentage
* @param {string} color The color to process
* @param {number} amount The amount to change the color by
* @returns {string} The HEX representation of the processed color
*/
export const darken = (color: string, amount: number) => {
color = color.indexOf('#') >= 0 ? color.substring(1, color.length) : color
amount = Math.trunc((255 * amount) / 100)
return `#${subtractLight(color.substring(0, 2), amount)}${subtractLight(
color.substring(2, 4),
amount
)}${subtractLight(color.substring(4, 6), amount)}`
}
/**
* Lightens a 6 char HEX color according to the passed percentage
* @param {string} color The color to change
* @param {number} amount The amount to change the color by
* @returns {string} The processed color represented as HEX
*/
export const lighten = (color: string, amount: number) => {
color = color.indexOf('#') >= 0 ? color.substring(1, color.length) : color
amount = Math.trunc((255 * amount) / 100)
return `#${addLight(color.substring(0, 2), amount)}${addLight(
color.substring(2, 4),
amount
)}${addLight(color.substring(4, 6), amount)}`
}
/* Suma el porcentaje indicado a un color (RR, GG o BB) hexadecimal para aclararlo */
/**
* Sums the passed percentage to the R, G or B of a HEX color
* @param {string} color The color to change
* @param {number} amount The amount to change the color by
* @returns {string} The processed part of the color
*/
const addLight = (color: string, amount: number) => {
const cc = parseInt(color, 16) + amount
const c = cc > 255 ? 255 : cc
return c.toString(16).length > 1 ? c.toString(16) : `0${c.toString(16)}`
}
/**
* Calculates luminance of an rgb color
* @param {number} r red
* @param {number} g green
* @param {number} b blue
*/
const luminanace = (r: number, g: number, b: number) => {
const a = [r, g, b].map((v) => {
v /= 255
return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4)
})
return a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722
}
/**
* Calculates contrast between two rgb colors
* @param {string} rgb1 rgb color 1
* @param {string} rgb2 rgb color 2
*/
const contrast = (rgb1: string[], rgb2: number[]) => {
return (
(luminanace(~~rgb1[0], ~~rgb1[1], ~~rgb1[2]) + 0.05) /
(luminanace(rgb2[0], rgb2[1], rgb2[2]) + 0.05)
)
}
/**
* Determines what the best text color is (black or white) based con the contrast with the background
* @param hexColor - Last selected color by the user
*/
export const calculateBestTextColor = (hexColor: string) => {
const rgbColor = hexToRGB(hexColor.substring(1))
const contrastWithBlack = contrast(rgbColor.split(','), [0, 0, 0])
return contrastWithBlack >= 12 ? '#000000' : '#FFFFFF'
}
/**
* Subtracts the indicated percentage to the R, G or B of a HEX color
* @param {string} color The color to change
* @param {number} amount The amount to change the color by
* @returns {string} The processed part of the color
*/
const subtractLight = (color: string, amount: number) => {
const cc = parseInt(color, 16) - amount
const c = cc < 0 ? 0 : cc
return c.toString(16).length > 1 ? c.toString(16) : `0${c.toString(16)}`
}
// 预设颜色
export const PREDEFINE_COLORS = [
'#ff4500',
'#ff8c00',
'#ffd700',
'#90ee90',
'#00ced1',
'#1e90ff',
'#c71585',
'#409EFF',
'#909399',
'#C0C4CC',
'#b7390b',
'#ff7800',
'#fad400',
'#5b8c5f',
'#00babd',
'#1f73c3',
'#711f57'
]
/**
* Mixes two colors.
*
* @param {string} color1 - The first color, should be a 6-digit hexadecimal color code starting with `#`.
* @param {string} color2 - The second color, should be a 6-digit hexadecimal color code starting with `#`.
* @param {number} [weight=0.5] - The weight of color1 in the mix, should be a number between 0 and 1, where 0 represents 100% of color2, and 1 represents 100% of color1.
* @returns {string} The mixed color, a 6-digit hexadecimal color code starting with `#`.
*/
export const mix = (color1: string, color2: string, weight: number = 0.5): string => {
let color = '#'
for (let i = 0; i <= 2; i++) {
const c1 = parseInt(color1.substring(1 + i * 2, 3 + i * 2), 16)
const c2 = parseInt(color2.substring(1 + i * 2, 3 + i * 2), 16)
const c = Math.round(c1 * weight + c2 * (1 - weight))
color += c.toString(16).padStart(2, '0')
}
return color
}
/**
* getCssColorVariable
* @description 获取css变量的颜色值
* @param colorVariable css变量名
* @param opacity 透明度
* @returns {string} 颜色值
* @example getCssColorVariable('--el-color-primary', 0.5)
* @example getCssColorVariable('--el-color-primary')
* @example getCssColorVariable()
*/
export const getCssColorVariable = (
colorVariable: string = '--el-color-primary',
opacity?: number
) => {
const colorValue = getComputedStyle(document.documentElement)
.getPropertyValue(colorVariable)
.trim()
if (colorValue) {
return opacity ? hexToRGB(colorValue, opacity) : colorValue
}
return ''
}

465
src/utils/constants.ts Normal file
View File

@@ -0,0 +1,465 @@
/**
* Created by 芋道源码
*
* 枚举类
*/
// ========== COMMON 模块 ==========
// 全局通用状态枚举
export const CommonStatusEnum = {
ENABLE: 0, // 开启
DISABLE: 1 // 禁用
}
// 全局用户类型枚举
export const UserTypeEnum = {
MEMBER: 1, // 会员
ADMIN: 2 // 管理员
}
// ========== SYSTEM 模块 ==========
/**
* 菜单的类型枚举
*/
export const SystemMenuTypeEnum = {
DIR: 1, // 目录
MENU: 2, // 菜单
BUTTON: 3 // 按钮
}
/**
* 角色的类型枚举
*/
export const SystemRoleTypeEnum = {
SYSTEM: 1, // 内置角色
CUSTOM: 2 // 自定义角色
}
/**
* 数据权限的范围枚举
*/
export const SystemDataScopeEnum = {
ALL: 1, // 全部数据权限
DEPT_CUSTOM: 2, // 指定部门数据权限
DEPT_ONLY: 3, // 部门数据权限
DEPT_AND_CHILD: 4, // 部门及以下数据权限
DEPT_SELF: 5 // 仅本人数据权限
}
/**
* 用户的社交平台的类型枚举
*/
export const SystemUserSocialTypeEnum = {
DINGTALK: {
title: '钉钉',
type: 20,
source: 'dingtalk',
img: 'https://s1.ax1x.com/2022/05/22/OzMDRs.png'
},
WECHAT_ENTERPRISE: {
title: '企业微信',
type: 30,
source: 'wechat_enterprise',
img: 'https://s1.ax1x.com/2022/05/22/OzMrzn.png'
}
}
// ========== INFRA 模块 ==========
/**
* 代码生成模板类型
*/
export const InfraCodegenTemplateTypeEnum = {
CRUD: 1, // 基础 CRUD
TREE: 2, // 树形 CRUD
SUB: 15 // 主子表 CRUD
}
/**
* 任务状态的枚举
*/
export const InfraJobStatusEnum = {
INIT: 0, // 初始化中
NORMAL: 1, // 运行中
STOP: 2 // 暂停运行
}
/**
* API 异常数据的处理状态
*/
export const InfraApiErrorLogProcessStatusEnum = {
INIT: 0, // 未处理
DONE: 1, // 已处理
IGNORE: 2 // 已忽略
}
// ========== PAY 模块 ==========
/**
* 支付渠道枚举
*/
export const PayChannelEnum = {
WX_PUB: {
code: 'wx_pub',
name: '微信 JSAPI 支付'
},
WX_LITE: {
code: 'wx_lite',
name: '微信小程序支付'
},
WX_APP: {
code: 'wx_app',
name: '微信 APP 支付'
},
WX_NATIVE: {
code: 'wx_native',
name: '微信 Native 支付'
},
WX_WAP: {
code: 'wx_wap',
name: '微信 WAP 网站支付'
},
WX_BAR: {
code: 'wx_bar',
name: '微信条码支付'
},
ALIPAY_PC: {
code: 'alipay_pc',
name: '支付宝 PC 网站支付'
},
ALIPAY_WAP: {
code: 'alipay_wap',
name: '支付宝 WAP 网站支付'
},
ALIPAY_APP: {
code: 'alipay_app',
name: '支付宝 APP 支付'
},
ALIPAY_QR: {
code: 'alipay_qr',
name: '支付宝扫码支付'
},
ALIPAY_BAR: {
code: 'alipay_bar',
name: '支付宝条码支付'
},
WALLET: {
code: 'wallet',
name: '钱包支付'
},
MOCK: {
code: 'mock',
name: '模拟支付'
}
}
/**
* 支付的展示模式每局
*/
export const PayDisplayModeEnum = {
URL: {
mode: 'url'
},
IFRAME: {
mode: 'iframe'
},
FORM: {
mode: 'form'
},
QR_CODE: {
mode: 'qr_code'
},
APP: {
mode: 'app'
}
}
/**
* 支付类型枚举
*/
export const PayType = {
WECHAT: 'WECHAT',
ALIPAY: 'ALIPAY',
MOCK: 'MOCK'
}
/**
* 支付订单状态枚举
*/
export const PayOrderStatusEnum = {
WAITING: {
status: 0,
name: '未支付'
},
SUCCESS: {
status: 10,
name: '已支付'
},
CLOSED: {
status: 20,
name: '未支付'
}
}
// ========== MALL - 商品模块 ==========
/**
* 商品 SPU 状态
*/
export const ProductSpuStatusEnum = {
RECYCLE: {
status: -1,
name: '回收站'
},
DISABLE: {
status: 0,
name: '下架'
},
ENABLE: {
status: 1,
name: '上架'
}
}
// ========== MALL - 营销模块 ==========
/**
* 优惠劵模板的有限期类型的枚举
*/
export const CouponTemplateValidityTypeEnum = {
DATE: {
type: 1,
name: '固定日期可用'
},
TERM: {
type: 2,
name: '领取之后可用'
}
}
/**
* 优惠劵模板的领取方式的枚举
*/
export const CouponTemplateTakeTypeEnum = {
USER: {
type: 1,
name: '直接领取'
},
ADMIN: {
type: 2,
name: '指定发放'
},
REGISTER: {
type: 3,
name: '新人券'
}
}
/**
* 营销的商品范围枚举
*/
export const PromotionProductScopeEnum = {
ALL: {
scope: 1,
name: '通用劵'
},
SPU: {
scope: 2,
name: '商品劵'
},
CATEGORY: {
scope: 3,
name: '品类劵'
}
}
/**
* 营销的条件类型枚举
*/
export const PromotionConditionTypeEnum = {
PRICE: {
type: 10,
name: '满 N 元'
},
COUNT: {
type: 20,
name: '满 N 件'
}
}
/**
* 优惠类型枚举
*/
export const PromotionDiscountTypeEnum = {
PRICE: {
type: 1,
name: '满减'
},
PERCENT: {
type: 2,
name: '折扣'
}
}
// ========== MALL - 交易模块 ==========
/**
* 分销关系绑定模式枚举
*/
export const BrokerageBindModeEnum = {
ANYTIME: {
mode: 1,
name: '首次绑定'
},
REGISTER: {
mode: 2,
name: '注册绑定'
},
OVERRIDE: {
mode: 3,
name: '覆盖绑定'
}
}
/**
* 分佣模式枚举
*/
export const BrokerageEnabledConditionEnum = {
ALL: {
condition: 1,
name: '人人分销'
},
ADMIN: {
condition: 2,
name: '指定分销'
}
}
/**
* 佣金记录业务类型枚举
*/
export const BrokerageRecordBizTypeEnum = {
ORDER: {
type: 1,
name: '获得推广佣金'
},
WITHDRAW: {
type: 2,
name: '提现申请'
}
}
/**
* 佣金提现状态枚举
*/
export const BrokerageWithdrawStatusEnum = {
AUDITING: {
status: 0,
name: '审核中'
},
AUDIT_SUCCESS: {
status: 10,
name: '审核通过'
},
AUDIT_FAIL: {
status: 20,
name: '审核不通过'
},
WITHDRAW_SUCCESS: {
status: 11,
name: '提现成功'
},
WITHDRAW_FAIL: {
status: 21,
name: '提现失败'
}
}
/**
* 佣金提现类型枚举
*/
export const BrokerageWithdrawTypeEnum = {
WALLET: {
type: 1,
name: '钱包'
},
BANK: {
type: 2,
name: '银行卡'
},
WECHAT: {
type: 3,
name: '微信'
},
ALIPAY: {
type: 4,
name: '支付宝'
}
}
/**
* 配送方式枚举
*/
export const DeliveryTypeEnum = {
EXPRESS: {
type: 1,
name: '快递发货'
},
PICK_UP: {
type: 2,
name: '到店自提'
}
}
/**
* 交易订单 - 状态
*/
export const TradeOrderStatusEnum = {
UNPAID: {
status: 0,
name: '待支付'
},
UNDELIVERED: {
status: 10,
name: '待发货'
},
DELIVERED: {
status: 20,
name: '已发货'
},
COMPLETED: {
status: 30,
name: '已完成'
},
CANCELED: {
status: 40,
name: '已取消'
}
}
// ========== ERP - 企业资源计划 ==========
export const ErpBizType = {
PURCHASE_ORDER: 10,
PURCHASE_IN: 11,
PURCHASE_RETURN: 12,
SALE_ORDER: 20,
SALE_OUT: 21,
SALE_RETURN: 22
}
// ========== BPM 模块 ==========
export const BpmModelType = {
BPMN: 10, // BPMN 设计器
SIMPLE: 20 // 简易设计器
}
export const BpmModelFormType = {
NORMAL: 10, // 流程表单
CUSTOM: 20 // 业务表单
}
export const BpmProcessInstanceStatus = {
NOT_START: -1, // 未开始
RUNNING: 1, // 审批中
APPROVE: 2, // 审批通过
REJECT: 3, // 审批不通过
CANCEL: 4 // 已取消
}
export const BpmAutoApproveType = {
NONE: 0, // 不自动通过
APPROVE_ALL: 1, // 仅审批一次,后续重复的审批节点均自动通过
APPROVE_SEQUENT: 2 // 仅针对连续审批的节点自动通过
}

18
src/utils/dateUtil.ts Normal file
View File

@@ -0,0 +1,18 @@
/**
* Independent time operation tool to facilitate subsequent switch to dayjs
*/
// TODO 芋艿:【锁屏】可能后面删除掉
import dayjs from 'dayjs'
const DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss'
const DATE_FORMAT = 'YYYY-MM-DD'
export function formatToDateTime(date?: dayjs.ConfigType, format = DATE_TIME_FORMAT): string {
return dayjs(date).format(format)
}
export function formatToDate(date?: dayjs.ConfigType, format = DATE_FORMAT): string {
return dayjs(date).format(format)
}
export const dateUtil = dayjs

254
src/utils/dict.ts Normal file
View File

@@ -0,0 +1,254 @@
/**
* 数据字典工具类
*/
import { OPERATION_BUTTON_NAME } from '@/components/SimpleProcessDesignerV2/src/consts'
import { useDictStoreWithOut } from '@/store/modules/dict'
import { ElementPlusInfoType } from '@/types/elementPlus'
const dictStore = useDictStoreWithOut()
/**
* 获取 dictType 对应的数据字典数组
*
* @param dictType 数据类型
* @returns {*|Array} 数据字典数组
*/
export interface DictDataType {
dictType: string
label: string
value: string | number | boolean
colorType: ElementPlusInfoType | ''
cssClass: string
}
export interface NumberDictDataType extends DictDataType {
value: number
}
export interface StringDictDataType extends DictDataType {
value: string
}
export const getDictOptions = (dictType: string) => {
return dictStore.getDictByType(dictType) || []
}
export const getIntDictOptions = (dictType: string): NumberDictDataType[] => {
// 获得通用的 DictDataType 列表
const dictOptions: DictDataType[] = getDictOptions(dictType)
// 转换成 number 类型的 NumberDictDataType 类型
// why 需要特殊转换:避免 IDEA 在 v-for="dict in getIntDictOptions(...)" 时el-option 的 key 会告警
const dictOption: NumberDictDataType[] = []
dictOptions.forEach((dict: DictDataType) => {
dictOption.push({
...dict,
value: parseInt(dict.value + '')
})
})
return dictOption
}
export const getStrDictOptions = (dictType: string) => {
// 获得通用的 DictDataType 列表
const dictOptions: DictDataType[] = getDictOptions(dictType)
// 转换成 string 类型的 StringDictDataType 类型
// why 需要特殊转换:避免 IDEA 在 v-for="dict in getStrDictOptions(...)" 时el-option 的 key 会告警
const dictOption: StringDictDataType[] = []
dictOptions.forEach((dict: DictDataType) => {
dictOption.push({
...dict,
value: dict.value + ''
})
})
return dictOption
}
export const getBoolDictOptions = (dictType: string) => {
const dictOption: DictDataType[] = []
const dictOptions: DictDataType[] = getDictOptions(dictType)
dictOptions.forEach((dict: DictDataType) => {
dictOption.push({
...dict,
value: dict.value + '' === 'true'
})
})
return dictOption
}
/**
* 获取指定字典类型的指定值对应的字典对象
* @param dictType 字典类型
* @param value 字典值
* @return DictDataType 字典对象
*/
export const getDictObj = (dictType: string, value: any): DictDataType | undefined => {
const dictOptions: DictDataType[] = getDictOptions(dictType)
for (const dict of dictOptions) {
if (dict.value === value + '') {
return dict
}
}
}
/**
* 获得字典数据的文本展示
*
* @param dictType 字典类型
* @param value 字典数据的值
* @return 字典名称
*/
export const getDictLabel = (dictType: string, value: any): string => {
const dictOptions: DictDataType[] = getDictOptions(dictType)
const dictLabel = ref('')
dictOptions.forEach((dict: DictDataType) => {
if (dict.value === value + '') {
dictLabel.value = dict.label
}
})
return dictLabel.value
}
export enum DICT_TYPE {
USER_TYPE = 'user_type',
COMMON_STATUS = 'common_status',
TERMINAL = 'terminal', // 终端
DATE_INTERVAL = 'date_interval', // 数据间隔
// ========== SYSTEM 模块 ==========
SYSTEM_USER_SEX = 'system_user_sex',
SYSTEM_MENU_TYPE = 'system_menu_type',
SYSTEM_ROLE_TYPE = 'system_role_type',
SYSTEM_DATA_SCOPE = 'system_data_scope',
SYSTEM_NOTICE_TYPE = 'system_notice_type',
SYSTEM_LOGIN_TYPE = 'system_login_type',
SYSTEM_LOGIN_RESULT = 'system_login_result',
SYSTEM_SMS_CHANNEL_CODE = 'system_sms_channel_code',
SYSTEM_SMS_TEMPLATE_TYPE = 'system_sms_template_type',
SYSTEM_SMS_SEND_STATUS = 'system_sms_send_status',
SYSTEM_SMS_RECEIVE_STATUS = 'system_sms_receive_status',
SYSTEM_OAUTH2_GRANT_TYPE = 'system_oauth2_grant_type',
SYSTEM_MAIL_SEND_STATUS = 'system_mail_send_status',
SYSTEM_NOTIFY_TEMPLATE_TYPE = 'system_notify_template_type',
SYSTEM_SOCIAL_TYPE = 'system_social_type',
// ========== INFRA 模块 ==========
INFRA_BOOLEAN_STRING = 'infra_boolean_string',
INFRA_JOB_STATUS = 'infra_job_status',
INFRA_JOB_LOG_STATUS = 'infra_job_log_status',
INFRA_API_ERROR_LOG_PROCESS_STATUS = 'infra_api_error_log_process_status',
INFRA_CONFIG_TYPE = 'infra_config_type',
INFRA_CODEGEN_TEMPLATE_TYPE = 'infra_codegen_template_type',
INFRA_CODEGEN_FRONT_TYPE = 'infra_codegen_front_type',
INFRA_CODEGEN_SCENE = 'infra_codegen_scene',
INFRA_FILE_STORAGE = 'infra_file_storage',
INFRA_OPERATE_TYPE = 'infra_operate_type',
// ========== BPM 模块 ==========
BPM_MODEL_TYPE = 'bpm_model_type',
BPM_MODEL_FORM_TYPE = 'bpm_model_form_type',
BPM_TASK_CANDIDATE_STRATEGY = 'bpm_task_candidate_strategy',
BPM_PROCESS_INSTANCE_STATUS = 'bpm_process_instance_status',
BPM_TASK_STATUS = 'bpm_task_status',
BPM_OA_LEAVE_TYPE = 'bpm_oa_leave_type',
BPM_PROCESS_LISTENER_TYPE = 'bpm_process_listener_type',
BPM_PROCESS_LISTENER_VALUE_TYPE = 'bpm_process_listener_value_type',
// ========== PAY 模块 ==========
PAY_CHANNEL_CODE = 'pay_channel_code', // 支付渠道编码类型
PAY_ORDER_STATUS = 'pay_order_status', // 商户支付订单状态
PAY_REFUND_STATUS = 'pay_refund_status', // 退款订单状态
PAY_NOTIFY_STATUS = 'pay_notify_status', // 商户支付回调状态
PAY_NOTIFY_TYPE = 'pay_notify_type', // 商户支付回调状态
PAY_TRANSFER_STATUS = 'pay_transfer_status', // 转账订单状态
// ========== MP 模块 ==========
MP_AUTO_REPLY_REQUEST_MATCH = 'mp_auto_reply_request_match', // 自动回复请求匹配类型
MP_MESSAGE_TYPE = 'mp_message_type', // 消息类型
// ========== Member 会员模块 ==========
MEMBER_POINT_BIZ_TYPE = 'member_point_biz_type', // 积分的业务类型
MEMBER_EXPERIENCE_BIZ_TYPE = 'member_experience_biz_type', // 会员经验业务类型
// ========== MALL - 商品模块 ==========
PRODUCT_SPU_STATUS = 'product_spu_status', //商品状态
// ========== MALL - 交易模块 ==========
EXPRESS_CHARGE_MODE = 'trade_delivery_express_charge_mode', //快递的计费方式
TRADE_AFTER_SALE_STATUS = 'trade_after_sale_status', // 售后 - 状态
TRADE_AFTER_SALE_WAY = 'trade_after_sale_way', // 售后 - 方式
TRADE_AFTER_SALE_TYPE = 'trade_after_sale_type', // 售后 - 类型
TRADE_ORDER_TYPE = 'trade_order_type', // 订单 - 类型
TRADE_ORDER_STATUS = 'trade_order_status', // 订单 - 状态
TRADE_ORDER_ITEM_AFTER_SALE_STATUS = 'trade_order_item_after_sale_status', // 订单项 - 售后状态
TRADE_DELIVERY_TYPE = 'trade_delivery_type', // 配送方式
BROKERAGE_ENABLED_CONDITION = 'brokerage_enabled_condition', // 分佣模式
BROKERAGE_BIND_MODE = 'brokerage_bind_mode', // 分销关系绑定模式
BROKERAGE_BANK_NAME = 'brokerage_bank_name', // 佣金提现银行
BROKERAGE_WITHDRAW_TYPE = 'brokerage_withdraw_type', // 佣金提现类型
BROKERAGE_RECORD_BIZ_TYPE = 'brokerage_record_biz_type', // 佣金业务类型
BROKERAGE_RECORD_STATUS = 'brokerage_record_status', // 佣金状态
BROKERAGE_WITHDRAW_STATUS = 'brokerage_withdraw_status', // 佣金提现状态
// ========== MALL - 营销模块 ==========
PROMOTION_DISCOUNT_TYPE = 'promotion_discount_type', // 优惠类型
PROMOTION_PRODUCT_SCOPE = 'promotion_product_scope', // 营销的商品范围
PROMOTION_COUPON_TEMPLATE_VALIDITY_TYPE = 'promotion_coupon_template_validity_type', // 优惠劵模板的有限期类型
PROMOTION_COUPON_STATUS = 'promotion_coupon_status', // 优惠劵的状态
PROMOTION_COUPON_TAKE_TYPE = 'promotion_coupon_take_type', // 优惠劵的领取方式
PROMOTION_CONDITION_TYPE = 'promotion_condition_type', // 营销的条件类型枚举
PROMOTION_BARGAIN_RECORD_STATUS = 'promotion_bargain_record_status', // 砍价记录的状态
PROMOTION_COMBINATION_RECORD_STATUS = 'promotion_combination_record_status', // 拼团记录的状态
PROMOTION_BANNER_POSITION = 'promotion_banner_position', // banner 定位
// ========== CRM - 客户管理模块 ==========
CRM_AUDIT_STATUS = 'crm_audit_status', // CRM 审批状态
CRM_BIZ_TYPE = 'crm_biz_type', // CRM 业务类型
CRM_BUSINESS_END_STATUS_TYPE = 'crm_business_end_status_type', // CRM 商机结束状态类型
CRM_RECEIVABLE_RETURN_TYPE = 'crm_receivable_return_type', // CRM 回款的还款方式
CRM_CUSTOMER_INDUSTRY = 'crm_customer_industry', // CRM 客户所属行业
CRM_CUSTOMER_LEVEL = 'crm_customer_level', // CRM 客户级别
CRM_CUSTOMER_SOURCE = 'crm_customer_source', // CRM 客户来源
CRM_PRODUCT_STATUS = 'crm_product_status', // CRM 商品状态
CRM_PERMISSION_LEVEL = 'crm_permission_level', // CRM 数据权限的级别
CRM_PRODUCT_UNIT = 'crm_product_unit', // CRM 产品单位
CRM_FOLLOW_UP_TYPE = 'crm_follow_up_type', // CRM 跟进方式
// ========== ERP - 企业资源计划模块 ==========
ERP_AUDIT_STATUS = 'erp_audit_status', // ERP 审批状态
ERP_STOCK_RECORD_BIZ_TYPE = 'erp_stock_record_biz_type', // 库存明细的业务类型
// ========== AI - 人工智能模块 ==========
AI_PLATFORM = 'ai_platform', // AI 平台
AI_MODEL_TYPE = 'ai_model_type', // AI 模型类型
AI_IMAGE_STATUS = 'ai_image_status', // AI 图片状态
AI_MUSIC_STATUS = 'ai_music_status', // AI 音乐状态
AI_GENERATE_MODE = 'ai_generate_mode', // AI 生成模式
AI_WRITE_TYPE = 'ai_write_type', // AI 写作类型
AI_WRITE_LENGTH = 'ai_write_length', // AI 写作长度
AI_WRITE_FORMAT = 'ai_write_format', // AI 写作格式
AI_WRITE_TONE = 'ai_write_tone', // AI 写作语气
AI_WRITE_LANGUAGE = 'ai_write_language', // AI 写作语言
// ========== IOT - 物联网模块 ==========
IOT_NET_TYPE = 'iot_net_type', // IOT 联网方式
IOT_VALIDATE_TYPE = 'iot_validate_type', // IOT 数据校验级别
IOT_PRODUCT_STATUS = 'iot_product_status', // IOT 产品状态
IOT_PRODUCT_DEVICE_TYPE = 'iot_product_device_type', // IOT 产品设备类型
IOT_DATA_FORMAT = 'iot_data_format', // IOT 数据格式
IOT_PROTOCOL_TYPE = 'iot_protocol_type', // IOT 接入网关协议
IOT_DEVICE_STATE = 'iot_device_state', // IOT 设备状态
IOT_THING_MODEL_TYPE = 'iot_thing_model_type', // IOT 产品功能类型
IOT_DATA_TYPE = 'iot_data_type', // IOT 数据类型
IOT_THING_MODEL_UNIT = 'iot_thing_model_unit', // IOT 物模型单位
IOT_RW_TYPE = 'iot_rw_type', // IOT 读写类型
IOT_PLUGIN_DEPLOY_TYPE = 'iot_plugin_deploy_type', // IOT 插件部署类型
IOT_PLUGIN_STATUS = 'iot_plugin_status', // IOT 插件状态
IOT_PLUGIN_TYPE = 'iot_plugin_type', // IOT 插件类型
IOT_DATA_BRIDGE_DIRECTION_ENUM = 'iot_data_bridge_direction_enum', // 桥梁方向
IOT_DATA_BRIDGE_TYPE_ENUM = 'iot_data_bridge_type_enum', // 桥梁类型
HOSTS_INVITATION_TYPE = 'hosts_Invitation_type' ,// 桥梁类型
INT_TRUE_FLASE = 'int_true_false',// 桥梁类型HOST_LEVEL
HOST_LEVEL = 'host_level', // 桥梁类型country_group
COUNTRY_GROUP = 'country_group', // 桥梁类型
OPERATION_STATE = 'operational_state' // 桥梁类型operational_state
}

289
src/utils/domUtils.ts Normal file
View File

@@ -0,0 +1,289 @@
import { isServer } from './is'
const ieVersion = isServer ? 0 : Number((document as any).documentMode)
const SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g
const MOZ_HACK_REGEXP = /^moz([A-Z])/
export interface ViewportOffsetResult {
left: number
top: number
right: number
bottom: number
rightIncludeBody: number
bottomIncludeBody: number
}
/* istanbul ignore next */
const trim = function (string: string) {
return (string || '').replace(/^[\s\uFEFF]+|[\s\uFEFF]+$/g, '')
}
/* istanbul ignore next */
const camelCase = function (name: string) {
return name
.replace(SPECIAL_CHARS_REGEXP, function (_, __, letter, offset) {
return offset ? letter.toUpperCase() : letter
})
.replace(MOZ_HACK_REGEXP, 'Moz$1')
}
/* istanbul ignore next */
export function hasClass(el: Element, cls: string) {
if (!el || !cls) return false
if (cls.indexOf(' ') !== -1) {
throw new Error('className should not contain space.')
}
if (el.classList) {
return el.classList.contains(cls)
} else {
return (' ' + el.className + ' ').indexOf(' ' + cls + ' ') > -1
}
}
/* istanbul ignore next */
export function addClass(el: Element, cls: string) {
if (!el) return
let curClass = el.className
const classes = (cls || '').split(' ')
for (let i = 0, j = classes.length; i < j; i++) {
const clsName = classes[i]
if (!clsName) continue
if (el.classList) {
el.classList.add(clsName)
} else if (!hasClass(el, clsName)) {
curClass += ' ' + clsName
}
}
if (!el.classList) {
el.className = curClass
}
}
/* istanbul ignore next */
export function removeClass(el: Element, cls: string) {
if (!el || !cls) return
const classes = cls.split(' ')
let curClass = ' ' + el.className + ' '
for (let i = 0, j = classes.length; i < j; i++) {
const clsName = classes[i]
if (!clsName) continue
if (el.classList) {
el.classList.remove(clsName)
} else if (hasClass(el, clsName)) {
curClass = curClass.replace(' ' + clsName + ' ', ' ')
}
}
if (!el.classList) {
el.className = trim(curClass)
}
}
export function getBoundingClientRect(element: Element): DOMRect | number {
if (!element || !element.getBoundingClientRect) {
return 0
}
return element.getBoundingClientRect()
}
/**
* 获取当前元素的left、top偏移
* left元素最左侧距离文档左侧的距离
* top:元素最顶端距离文档顶端的距离
* right:元素最右侧距离文档右侧的距离
* bottom元素最底端距离文档底端的距离
* rightIncludeBody元素最左侧距离文档右侧的距离
* bottomIncludeBody元素最底端距离文档最底部的距离
*
* @description:
*/
export function getViewportOffset(element: Element): ViewportOffsetResult {
const doc = document.documentElement
const docScrollLeft = doc.scrollLeft
const docScrollTop = doc.scrollTop
const docClientLeft = doc.clientLeft
const docClientTop = doc.clientTop
const pageXOffset = window.pageXOffset
const pageYOffset = window.pageYOffset
const box = getBoundingClientRect(element)
const { left: retLeft, top: rectTop, width: rectWidth, height: rectHeight } = box as DOMRect
const scrollLeft = (pageXOffset || docScrollLeft) - (docClientLeft || 0)
const scrollTop = (pageYOffset || docScrollTop) - (docClientTop || 0)
const offsetLeft = retLeft + pageXOffset
const offsetTop = rectTop + pageYOffset
const left = offsetLeft - scrollLeft
const top = offsetTop - scrollTop
const clientWidth = window.document.documentElement.clientWidth
const clientHeight = window.document.documentElement.clientHeight
return {
left: left,
top: top,
right: clientWidth - rectWidth - left,
bottom: clientHeight - rectHeight - top,
rightIncludeBody: clientWidth - left,
bottomIncludeBody: clientHeight - top
}
}
/* istanbul ignore next */
export const on = function (
element: HTMLElement | Document | Window,
event: string,
handler: EventListenerOrEventListenerObject
): void {
if (element && event && handler) {
element.addEventListener(event, handler, false)
}
}
/* istanbul ignore next */
export const off = function (
element: HTMLElement | Document | Window,
event: string,
handler: any
): void {
if (element && event && handler) {
element.removeEventListener(event, handler, false)
}
}
/* istanbul ignore next */
export const once = function (el: HTMLElement, event: string, fn: EventListener): void {
const listener = function (this: any, ...args: unknown[]) {
if (fn) {
// @ts-ignore
fn.apply(this, args)
}
off(el, event, listener)
}
on(el, event, listener)
}
/* istanbul ignore next */
export const getStyle =
ieVersion < 9
? function (element: Element | any, styleName: string) {
if (isServer) return
if (!element || !styleName) return null
styleName = camelCase(styleName)
if (styleName === 'float') {
styleName = 'styleFloat'
}
try {
switch (styleName) {
case 'opacity':
try {
return element.filters.item('alpha').opacity / 100
} catch (e) {
return 1.0
}
default:
return element.style[styleName] || element.currentStyle
? element.currentStyle[styleName]
: null
}
} catch (e) {
return element.style[styleName]
}
}
: function (element: Element | any, styleName: string) {
if (isServer) return
if (!element || !styleName) return null
styleName = camelCase(styleName)
if (styleName === 'float') {
styleName = 'cssFloat'
}
try {
const computed = (document as any).defaultView.getComputedStyle(element, '')
return element.style[styleName] || computed ? computed[styleName] : null
} catch (e) {
return element.style[styleName]
}
}
/* istanbul ignore next */
export function setStyle(element: Element | any, styleName: any, value: any) {
if (!element || !styleName) return
if (typeof styleName === 'object') {
for (const prop in styleName) {
if (Object.prototype.hasOwnProperty.call(styleName, prop)) {
setStyle(element, prop, styleName[prop])
}
}
} else {
styleName = camelCase(styleName)
if (styleName === 'opacity' && ieVersion < 9) {
element.style.filter = isNaN(value) ? '' : 'alpha(opacity=' + value * 100 + ')'
} else {
element.style[styleName] = value
}
}
}
/* istanbul ignore next */
export const isScroll = (el: Element, vertical: any) => {
if (isServer) return
const determinedDirection = vertical !== null || vertical !== undefined
const overflow = determinedDirection
? vertical
? getStyle(el, 'overflow-y')
: getStyle(el, 'overflow-x')
: getStyle(el, 'overflow')
return overflow.match(/(scroll|auto)/)
}
/* istanbul ignore next */
export const getScrollContainer = (el: Element, vertical?: any) => {
if (isServer) return
let parent: any = el
while (parent) {
if ([window, document, document.documentElement].includes(parent)) {
return window
}
if (isScroll(parent, vertical)) {
return parent
}
parent = parent.parentNode
}
return parent
}
/* istanbul ignore next */
export const isInContainer = (el: Element, container: any) => {
if (isServer || !el || !container) return false
const elRect = el.getBoundingClientRect()
let containerRect
if ([window, document, document.documentElement, null, undefined].includes(container)) {
containerRect = {
top: 0,
right: window.innerWidth,
bottom: window.innerHeight,
left: 0
}
} else {
containerRect = container.getBoundingClientRect()
}
return (
elRect.top < containerRect.bottom &&
elRect.bottom > containerRect.top &&
elRect.right > containerRect.left &&
elRect.left < containerRect.right
)
}

100
src/utils/download.ts Normal file
View File

@@ -0,0 +1,100 @@
const download0 = (data: Blob, fileName: string, mineType: string) => {
// 创建 blob
const blob = new Blob([data], { type: mineType })
// 创建 href 超链接,点击进行下载
window.URL = window.URL || window.webkitURL
const href = URL.createObjectURL(blob)
const downA = document.createElement('a')
downA.href = href
downA.download = fileName
downA.click()
// 销毁超连接
window.URL.revokeObjectURL(href)
}
const download = {
// 下载 Excel 方法
excel: (data: Blob, fileName: string) => {
download0(data, fileName, 'application/vnd.ms-excel')
},
// 下载 Word 方法
word: (data: Blob, fileName: string) => {
download0(data, fileName, 'application/msword')
},
// 下载 Zip 方法
zip: (data: Blob, fileName: string) => {
download0(data, fileName, 'application/zip')
},
// 下载 Html 方法
html: (data: Blob, fileName: string) => {
download0(data, fileName, 'text/html')
},
// 下载 Markdown 方法
markdown: (data: Blob, fileName: string) => {
download0(data, fileName, 'text/markdown')
},
// 下载 Json 方法
json: (data: Blob, fileName: string) => {
download0(data, fileName, 'application/json')
},
// 下载图片(允许跨域)
image: ({
url,
canvasWidth,
canvasHeight,
drawWithImageSize = true
}: {
url: string
canvasWidth?: number // 指定画布宽度
canvasHeight?: number // 指定画布高度
drawWithImageSize?: boolean // 将图片绘制在画布上时带上图片的宽高值, 默认是要带上的
}) => {
const image = new Image()
// image.setAttribute('crossOrigin', 'anonymous')
image.src = url
image.onload = () => {
const canvas = document.createElement('canvas')
canvas.width = canvasWidth || image.width
canvas.height = canvasHeight || image.height
const ctx = canvas.getContext('2d') as CanvasRenderingContext2D
ctx?.clearRect(0, 0, canvas.width, canvas.height)
if (drawWithImageSize) {
ctx.drawImage(image, 0, 0, image.width, image.height)
} else {
ctx.drawImage(image, 0, 0)
}
const url = canvas.toDataURL('image/png')
const a = document.createElement('a')
a.href = url
a.download = 'image.png'
a.click()
}
},
base64ToFile: (base64: any, fileName: string) => {
// 将base64按照 , 进行分割 将前缀 与后续内容分隔开
const data = base64.split(',')
// 利用正则表达式 从前缀中获取图片的类型信息image/png、image/jpeg、image/webp等
const type = data[0].match(/:(.*?);/)[1]
// 从图片的类型信息中 获取具体的文件格式后缀png、jpeg、webp
const suffix = type.split('/')[1]
// 使用atob()对base64数据进行解码 结果是一个文件数据流 以字符串的格式输出
const bstr = window.atob(data[1])
// 获取解码结果字符串的长度
let n = bstr.length
// 根据解码结果字符串的长度创建一个等长的整形数字数组
// 但在创建时 所有元素初始值都为 0
const u8arr = new Uint8Array(n)
// 将整形数组的每个元素填充为解码结果字符串对应位置字符的UTF-16 编码单元
while (n--) {
// charCodeAt():获取给定索引处字符对应的 UTF-16 代码单元
u8arr[n] = bstr.charCodeAt(n)
}
// 将File文件对象返回给方法的调用者
return new File([u8arr], `${fileName}.${suffix}`, {
type: type
})
}
}
export default download

157
src/utils/filt.ts Normal file
View File

@@ -0,0 +1,157 @@
export const openWindow = (
url: string,
opt?: {
target?: '_self' | '_blank' | string
noopener?: boolean
noreferrer?: boolean
}
) => {
const { target = '__blank', noopener = true, noreferrer = true } = opt || {}
const feature: string[] = []
noopener && feature.push('noopener=yes')
noreferrer && feature.push('noreferrer=yes')
window.open(url, target, feature.join(','))
}
/**
* @description: base64 to blob
*/
export const dataURLtoBlob = (base64Buf: string): Blob => {
const arr = base64Buf.split(',')
const typeItem = arr[0]
const mime = typeItem.match(/:(.*?);/)![1]
const bstr = window.atob(arr[1])
let n = bstr.length
const u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new Blob([u8arr], { type: mime })
}
/**
* img url to base64
* @param url
*/
export const urlToBase64 = (url: string, mineType?: string): Promise<string> => {
return new Promise((resolve, reject) => {
let canvas = document.createElement('CANVAS') as Nullable<HTMLCanvasElement>
const ctx = canvas!.getContext('2d')
const img = new Image()
img.crossOrigin = ''
img.onload = function () {
if (!canvas || !ctx) {
return reject()
}
canvas.height = img.height
canvas.width = img.width
ctx.drawImage(img, 0, 0)
const dataURL = canvas.toDataURL(mineType || 'image/png')
canvas = null
resolve(dataURL)
}
img.src = url
})
}
/**
* Download online pictures
* @param url
* @param filename
* @param mime
* @param bom
*/
export const downloadByOnlineUrl = (
url: string,
filename: string,
mime?: string,
bom?: BlobPart
) => {
urlToBase64(url).then((base64) => {
downloadByBase64(base64, filename, mime, bom)
})
}
/**
* Download pictures based on base64
* @param buf
* @param filename
* @param mime
* @param bom
*/
export const downloadByBase64 = (buf: string, filename: string, mime?: string, bom?: BlobPart) => {
const base64Buf = dataURLtoBlob(buf)
downloadByData(base64Buf, filename, mime, bom)
}
/**
* Download according to the background interface file stream
* @param {*} data
* @param {*} filename
* @param {*} mime
* @param {*} bom
*/
export const downloadByData = (data: BlobPart, filename: string, mime?: string, bom?: BlobPart) => {
const blobData = typeof bom !== 'undefined' ? [bom, data] : [data]
const blob = new Blob(blobData, { type: mime || 'application/octet-stream' })
const blobURL = window.URL.createObjectURL(blob)
const tempLink = document.createElement('a')
tempLink.style.display = 'none'
tempLink.href = blobURL
tempLink.setAttribute('download', filename)
if (typeof tempLink.download === 'undefined') {
tempLink.setAttribute('target', '_blank')
}
document.body.appendChild(tempLink)
tempLink.click()
document.body.removeChild(tempLink)
window.URL.revokeObjectURL(blobURL)
}
/**
* Download file according to file address
* @param {*} sUrl
*/
export const downloadByUrl = ({
url,
target = '_blank',
fileName
}: {
url: string
target?: '_self' | '_blank'
fileName?: string
}): boolean => {
const isChrome = window.navigator.userAgent.toLowerCase().indexOf('chrome') > -1
const isSafari = window.navigator.userAgent.toLowerCase().indexOf('safari') > -1
if (/(iP)/g.test(window.navigator.userAgent)) {
console.error('Your browser does not support download!')
return false
}
if (isChrome || isSafari) {
const link = document.createElement('a')
link.href = url
link.target = target
if (link.download !== undefined) {
link.download = fileName || url.substring(url.lastIndexOf('/') + 1, url.length)
}
if (document.createEvent) {
const e = document.createEvent('MouseEvents')
e.initEvent('click', true, true)
link.dispatchEvent(e)
return true
}
}
if (url.indexOf('?') === -1) {
url += '?download'
}
openWindow(url, { target })
return true
}

58
src/utils/formCreate.ts Normal file
View File

@@ -0,0 +1,58 @@
/**
* 针对 https://github.com/xaboy/form-create-designer 封装的工具类
*/
// 编码表单 Conf
export const encodeConf = (designerRef: object) => {
// @ts-ignore
return JSON.stringify(designerRef.value.getOption())
}
// 编码表单 Fields
export const encodeFields = (designerRef: object) => {
// @ts-ignore
const rule = JSON.parse(designerRef.value.getJson())
const fields: string[] = []
rule.forEach((item) => {
fields.push(JSON.stringify(item))
})
return fields
}
// 解码表单 Fields
export const decodeFields = (fields: string[]) => {
const rule: object[] = []
fields.forEach((item) => {
rule.push(JSON.parse(item))
})
return rule
}
// 设置表单的 Conf 和 Fields适用 FcDesigner 场景
export const setConfAndFields = (designerRef: object, conf: string, fields: string) => {
// @ts-ignore
designerRef.value.setOption(JSON.parse(conf))
// @ts-ignore
designerRef.value.setRule(decodeFields(fields))
}
// 设置表单的 Conf 和 Fields适用 form-create 场景
export const setConfAndFields2 = (
detailPreview: object,
conf: string,
fields: string[],
value?: object
) => {
if (isRef(detailPreview)) {
// @ts-ignore
detailPreview = detailPreview.value
}
// @ts-ignore
detailPreview.option = JSON.parse(conf)
// @ts-ignore
detailPreview.rule = decodeFields(fields)
if (value) {
// @ts-ignore
detailPreview.value = value
}
}

7
src/utils/formRules.ts Normal file
View File

@@ -0,0 +1,7 @@
const { t } = useI18n()
// 必填项
export const required = {
required: true,
message: t('common.required')
}

332
src/utils/formatTime.ts Normal file
View File

@@ -0,0 +1,332 @@
import dayjs from 'dayjs'
import type { TableColumnCtx } from 'element-plus'
/**
* 日期快捷选项适用于 el-date-picker
*/
export const defaultShortcuts = [
{
text: '今天',
value: () => {
return new Date()
}
},
{
text: '昨天',
value: () => {
const date = new Date()
date.setTime(date.getTime() - 3600 * 1000 * 24)
return [date, date]
}
},
{
text: '最近七天',
value: () => {
const date = new Date()
date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
return [date, new Date()]
}
},
{
text: '最近 30 天',
value: () => {
const date = new Date()
date.setTime(date.getTime() - 3600 * 1000 * 24 * 30)
return [date, new Date()]
}
},
{
text: '本月',
value: () => {
const date = new Date()
date.setDate(1) // 设置为当前月的第一天
return [date, new Date()]
}
},
{
text: '今年',
value: () => {
const date = new Date()
return [new Date(`${date.getFullYear()}-01-01`), date]
}
}
]
/**
* 时间日期转换
* @param date 当前时间new Date() 格式
* @param format 需要转换的时间格式字符串
* @description format 字符串随意,如 `YYYY-MM、YYYY-MM-DD`
* @description format 季度:"YYYY-MM-DD HH:mm:ss QQQQ"
* @description format 星期:"YYYY-MM-DD HH:mm:ss WWW"
* @description format 几周:"YYYY-MM-DD HH:mm:ss ZZZ"
* @description format 季度 + 星期 + 几周:"YYYY-MM-DD HH:mm:ss WWW QQQQ ZZZ"
* @returns 返回拼接后的时间字符串
*/
export function formatDate(date: Date, format?: string): string {
// 日期不存在,则返回空
if (!date) {
return ''
}
// 日期存在,则进行格式化
return date ? dayjs(date).format(format ?? 'YYYY-MM-DD HH:mm:ss') : ''
}
/**
* 获取当前的日期+时间
*/
export function getNowDateTime() {
return dayjs()
}
/**
* 获取当前日期是第几周
* @param dateTime 当前传入的日期值
* @returns 返回第几周数字值
*/
export function getWeek(dateTime: Date): number {
const temptTime = new Date(dateTime.getTime())
// 周几
const weekday = temptTime.getDay() || 7
// 周1+5天=周六
temptTime.setDate(temptTime.getDate() - weekday + 1 + 5)
let firstDay = new Date(temptTime.getFullYear(), 0, 1)
const dayOfWeek = firstDay.getDay()
let spendDay = 1
if (dayOfWeek != 0) spendDay = 7 - dayOfWeek + 1
firstDay = new Date(temptTime.getFullYear(), 0, 1 + spendDay)
const d = Math.ceil((temptTime.valueOf() - firstDay.valueOf()) / 86400000)
return Math.ceil(d / 7)
}
/**
* 将时间转换为 `几秒前`、`几分钟前`、`几小时前`、`几天前`
* @param param 当前时间new Date() 格式或者字符串时间格式
* @param format 需要转换的时间格式字符串
* @description param 10秒 10 * 1000
* @description param 1分 60 * 1000
* @description param 1小时 60 * 60 * 1000
* @description param 24小时60 * 60 * 24 * 1000
* @description param 3天 60 * 60* 24 * 1000 * 3
* @returns 返回拼接后的时间字符串
*/
export function formatPast(param: string | Date, format = 'YYYY-MM-DD HH:mm:ss'): string {
// 传入格式处理、存储转换值
let t: any, s: number
// 获取js 时间戳
let time: number = new Date().getTime()
// 是否是对象
typeof param === 'string' || 'object' ? (t = new Date(param).getTime()) : (t = param)
// 当前时间戳 - 传入时间戳
time = Number.parseInt(`${time - t}`)
if (time < 10000) {
// 10秒内
return '刚刚'
} else if (time < 60000 && time >= 10000) {
// 超过10秒少于1分钟内
s = Math.floor(time / 1000)
return `${s}秒前`
} else if (time < 3600000 && time >= 60000) {
// 超过1分钟少于1小时
s = Math.floor(time / 60000)
return `${s}分钟前`
} else if (time < 86400000 && time >= 3600000) {
// 超过1小时少于24小时
s = Math.floor(time / 3600000)
return `${s}小时前`
} else if (time < 259200000 && time >= 86400000) {
// 超过1天少于3天内
s = Math.floor(time / 86400000)
return `${s}天前`
} else {
// 超过3天
const date = typeof param === 'string' || 'object' ? new Date(param) : param
return formatDate(date, format)
}
}
/**
* 时间问候语
* @param param 当前时间new Date() 格式
* @description param 调用 `formatAxis(new Date())` 输出 `上午好`
* @returns 返回拼接后的时间字符串
*/
export function formatAxis(param: Date): string {
const hour: number = new Date(param).getHours()
if (hour < 6) return '凌晨好'
else if (hour < 9) return '早上好'
else if (hour < 12) return '上午好'
else if (hour < 14) return '中午好'
else if (hour < 17) return '下午好'
else if (hour < 19) return '傍晚好'
else if (hour < 22) return '晚上好'
else return '夜里好'
}
/**
* 将毫秒转换成时间字符串。例如说xx 分钟
*
* @param ms 毫秒
* @returns {string} 字符串
*/
export function formatPast2(ms: number): string {
const day = Math.floor(ms / (24 * 60 * 60 * 1000))
const hour = Math.floor(ms / (60 * 60 * 1000) - day * 24)
const minute = Math.floor(ms / (60 * 1000) - day * 24 * 60 - hour * 60)
const second = Math.floor(ms / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60)
if (day > 0) {
return day + ' 天' + hour + ' 小时 ' + minute + ' 分钟'
}
if (hour > 0) {
return hour + ' 小时 ' + minute + ' 分钟'
}
if (minute > 0) {
return minute + ' 分钟'
}
if (second > 0) {
return second + ' 秒'
} else {
return 0 + ' 秒'
}
}
/**
* element plus 的时间 Formatter 实现,使用 YYYY-MM-DD HH:mm:ss 格式
*
* @param row 行数据
* @param column 字段
* @param cellValue 字段值
*/
export function dateFormatter(_row: any, _column: TableColumnCtx<any>, cellValue: any): string {
return cellValue ? formatDate(cellValue) : ''
}
/**
* element plus 的时间 Formatter 实现,使用 YYYY-MM-DD 格式
*
* @param row 行数据
* @param column 字段
* @param cellValue 字段值
*/
export function dateFormatter2(_row: any, _column: TableColumnCtx<any>, cellValue: any): string {
return cellValue ? formatDate(cellValue, 'YYYY-MM-DD') : ''
}
/**
* 设置起始日期时间为00:00:00
* @param param 传入日期
* @returns 带时间00:00:00的日期
*/
export function beginOfDay(param: Date): Date {
return new Date(param.getFullYear(), param.getMonth(), param.getDate(), 0, 0, 0)
}
/**
* 设置结束日期时间为23:59:59
* @param param 传入日期
* @returns 带时间23:59:59的日期
*/
export function endOfDay(param: Date): Date {
return new Date(param.getFullYear(), param.getMonth(), param.getDate(), 23, 59, 59)
}
/**
* 计算两个日期间隔天数
* @param param1 日期1
* @param param2 日期2
*/
export function betweenDay(param1: Date, param2: Date): number {
param1 = convertDate(param1)
param2 = convertDate(param2)
// 计算差值
return Math.floor((param2.getTime() - param1.getTime()) / (24 * 3600 * 1000))
}
/**
* 日期计算
* @param param1 日期
* @param param2 添加的时间
*/
export function addTime(param1: Date, param2: number): Date {
param1 = convertDate(param1)
return new Date(param1.getTime() + param2)
}
/**
* 日期转换
* @param param 日期
*/
export function convertDate(param: Date | string): Date {
if (typeof param === 'string') {
return new Date(param)
}
return param
}
/**
* 指定的两个日期, 是否为同一天
* @param a 日期 A
* @param b 日期 B
*/
export function isSameDay(a: dayjs.ConfigType, b: dayjs.ConfigType): boolean {
if (!a || !b) return false
const aa = dayjs(a)
const bb = dayjs(b)
return aa.year() == bb.year() && aa.month() == bb.month() && aa.day() == bb.day()
}
/**
* 获取一天的开始时间、截止时间
* @param date 日期
* @param days 天数
*/
export function getDayRange(
date: dayjs.ConfigType,
days: number
): [dayjs.ConfigType, dayjs.ConfigType] {
const day = dayjs(date).add(days, 'd')
return getDateRange(day, day)
}
/**
* 获取最近7天的开始时间、截止时间
*/
export function getLast7Days(): [dayjs.ConfigType, dayjs.ConfigType] {
const lastWeekDay = dayjs().subtract(7, 'd')
const yesterday = dayjs().subtract(1, 'd')
return getDateRange(lastWeekDay, yesterday)
}
/**
* 获取最近30天的开始时间、截止时间
*/
export function getLast30Days(): [dayjs.ConfigType, dayjs.ConfigType] {
const lastMonthDay = dayjs().subtract(30, 'd')
const yesterday = dayjs().subtract(1, 'd')
return getDateRange(lastMonthDay, yesterday)
}
/**
* 获取最近1年的开始时间、截止时间
*/
export function getLast1Year(): [dayjs.ConfigType, dayjs.ConfigType] {
const lastYearDay = dayjs().subtract(1, 'y')
const yesterday = dayjs().subtract(1, 'd')
return getDateRange(lastYearDay, yesterday)
}
/**
* 获取指定日期的开始时间、截止时间
* @param beginDate 开始日期
* @param endDate 截止日期
*/
export function getDateRange(
beginDate: dayjs.ConfigType,
endDate: dayjs.ConfigType
): [string, string] {
return [
dayjs(beginDate).startOf('d').format('YYYY-MM-DD HH:mm:ss'),
dayjs(endDate).endOf('d').format('YYYY-MM-DD HH:mm:ss')
]
}

7
src/utils/formatter.ts Normal file
View File

@@ -0,0 +1,7 @@
import { floatToFixed2 } from '@/utils'
// 格式化金额【分转元】
// @ts-ignore
export const fenToYuanFormat = (_, __, cellValue: any, ___) => {
return `${floatToFixed2(cellValue)}`
}

538
src/utils/index.ts Normal file
View File

@@ -0,0 +1,538 @@
import { toNumber } from 'lodash-es'
/**
*
* @param component 需要注册的组件
* @param alias 组件别名
* @returns any
*/
export const withInstall = <T>(component: T, alias?: string) => {
const comp = component as any
comp.install = (app: any) => {
app.component(comp.name || comp.displayName, component)
if (alias) {
app.config.globalProperties[alias] = component
}
}
return component as T & Plugin
}
/**
* @param str 需要转下划线的驼峰字符串
* @returns 字符串下划线
*/
export const humpToUnderline = (str: string): string => {
return str.replace(/([A-Z])/g, '-$1').toLowerCase()
}
/**
* @param str 需要转驼峰的下划线字符串
* @returns 字符串驼峰
*/
export const underlineToHump = (str: string): string => {
if (!str) return ''
return str.replace(/\-(\w)/g, (_, letter: string) => {
return letter.toUpperCase()
})
}
/**
* 驼峰转横杠
*/
export const humpToDash = (str: string): string => {
return str.replace(/([A-Z])/g, '-$1').toLowerCase()
}
export const setCssVar = (prop: string, val: any, dom = document.documentElement) => {
dom.style.setProperty(prop, val)
}
/**
* 查找数组对象的某个下标
* @param {Array} ary 查找的数组
* @param {Functon} fn 判断的方法
*/
// eslint-disable-next-line
export const findIndex = <T = Recordable>(ary: Array<T>, fn: Fn): number => {
if (ary.findIndex) {
return ary.findIndex(fn)
}
let index = -1
ary.some((item: T, i: number, ary: Array<T>) => {
const ret: T = fn(item, i, ary)
if (ret) {
index = i
return ret
}
})
return index
}
export const trim = (str: string) => {
return str.replace(/(^\s*)|(\s*$)/g, '')
}
/**
* @param {Date | number | string} time 需要转换的时间
* @param {String} fmt 需要转换的格式 如 yyyy-MM-dd、yyyy-MM-dd HH:mm:ss
*/
export function formatTime(time: Date | number | string, fmt: string) {
if (!time) return ''
else {
const date = new Date(time)
const o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'H+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds(),
'q+': Math.floor((date.getMonth() + 3) / 3),
S: date.getMilliseconds()
}
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
}
for (const k in o) {
if (new RegExp('(' + k + ')').test(fmt)) {
fmt = fmt.replace(
RegExp.$1,
RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
)
}
}
return fmt
}
}
/**
* 生成随机字符串
*/
export function toAnyString() {
const str: string = 'xxxxx-xxxxx-4xxxx-yxxxx-xxxxx'.replace(/[xy]/g, (c: string) => {
const r: number = (Math.random() * 16) | 0
const v: number = c === 'x' ? r : (r & 0x3) | 0x8
return v.toString()
})
return str
}
/**
* 生成指定长度的随机字符串
*
* @param length 字符串长度
*/
export function generateRandomStr(length: number): string {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
let result = ''
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length))
}
return result
}
/**
* 根据支持的文件类型生成 accept 属性值
*
* @param supportedFileTypes 支持的文件类型数组,如 ['PDF', 'DOC', 'DOCX']
* @returns 用于文件上传组件 accept 属性的字符串
*/
export const generateAcceptedFileTypes = (supportedFileTypes: string[]): string => {
const allowedExtensions = supportedFileTypes.map((ext) => ext.toLowerCase())
const mimeTypes: string[] = []
// 添加常见的 MIME 类型映射
if (allowedExtensions.includes('txt')) {
mimeTypes.push('text/plain')
}
if (allowedExtensions.includes('pdf')) {
mimeTypes.push('application/pdf')
}
if (allowedExtensions.includes('html') || allowedExtensions.includes('htm')) {
mimeTypes.push('text/html')
}
if (allowedExtensions.includes('csv')) {
mimeTypes.push('text/csv')
}
if (allowedExtensions.includes('xlsx') || allowedExtensions.includes('xls')) {
mimeTypes.push('application/vnd.ms-excel')
mimeTypes.push('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
}
if (allowedExtensions.includes('docx') || allowedExtensions.includes('doc')) {
mimeTypes.push('application/msword')
mimeTypes.push('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
}
if (allowedExtensions.includes('pptx') || allowedExtensions.includes('ppt')) {
mimeTypes.push('application/vnd.ms-powerpoint')
mimeTypes.push('application/vnd.openxmlformats-officedocument.presentationml.presentation')
}
if (allowedExtensions.includes('xml')) {
mimeTypes.push('application/xml')
mimeTypes.push('text/xml')
}
if (allowedExtensions.includes('md') || allowedExtensions.includes('markdown')) {
mimeTypes.push('text/markdown')
}
if (allowedExtensions.includes('epub')) {
mimeTypes.push('application/epub+zip')
}
if (allowedExtensions.includes('eml')) {
mimeTypes.push('message/rfc822')
}
if (allowedExtensions.includes('msg')) {
mimeTypes.push('application/vnd.ms-outlook')
}
// 添加文件扩展名
const extensions = allowedExtensions.map((ext) => `.${ext}`)
return [...mimeTypes, ...extensions].join(',')
}
/**
* 首字母大写
*/
export function firstUpperCase(str: string) {
return str.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase())
}
export const generateUUID = () => {
if (typeof crypto === 'object') {
if (typeof crypto.randomUUID === 'function') {
return crypto.randomUUID()
}
if (typeof crypto.getRandomValues === 'function' && typeof Uint8Array === 'function') {
const callback = (c: any) => {
const num = Number(c)
return (num ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (num / 4)))).toString(
16
)
}
return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, callback)
}
}
let timestamp = new Date().getTime()
let performanceNow =
(typeof performance !== 'undefined' && performance.now && performance.now() * 1000) || 0
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
let random = Math.random() * 16
if (timestamp > 0) {
random = (timestamp + random) % 16 | 0
timestamp = Math.floor(timestamp / 16)
} else {
random = (performanceNow + random) % 16 | 0
performanceNow = Math.floor(performanceNow / 16)
}
return (c === 'x' ? random : (random & 0x3) | 0x8).toString(16)
})
}
/**
* element plus 的文件大小 Formatter 实现
*
* @param row 行数据
* @param column 字段
* @param cellValue 字段值
*/
// @ts-ignore
export const fileSizeFormatter = (row, column, cellValue) => {
const fileSize = cellValue
const unitArr = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
const srcSize = parseFloat(fileSize)
const index = Math.floor(Math.log(srcSize) / Math.log(1024))
const size = srcSize / Math.pow(1024, index)
const sizeStr = size.toFixed(2) //保留的小数位数
return sizeStr + ' ' + unitArr[index]
}
/**
* 将值复制到目标对象且以目标对象属性为准target: {a:1} source:{a:2,b:3} 结果为:{a:2}
* @param target 目标对象
* @param source 源对象
*/
export const copyValueToTarget = (target: any, source: any) => {
const newObj = Object.assign({}, target, source)
// 删除多余属性
Object.keys(newObj).forEach((key) => {
// 如果不是target中的属性则删除
if (Object.keys(target).indexOf(key) === -1) {
delete newObj[key]
}
})
// 更新目标对象值
Object.assign(target, newObj)
}
/**
* 获取链接的参数值
* @param key 参数键名
* @param urlStr 链接地址,默认为当前浏览器的地址
*/
export const getUrlValue = (key: string, urlStr: string = location.href): string => {
if (!urlStr || !key) return ''
const url = new URL(decodeURIComponent(urlStr))
return url.searchParams.get(key) ?? ''
}
/**
* 获取链接的参数值(值类型)
* @param key 参数键名
* @param urlStr 链接地址,默认为当前浏览器的地址
*/
export const getUrlNumberValue = (key: string, urlStr: string = location.href): number => {
return toNumber(getUrlValue(key, urlStr))
}
/**
* 构建排序字段
* @param prop 字段名称
* @param order 顺序
*/
export const buildSortingField = ({ prop, order }) => {
return { field: prop, order: order === 'ascending' ? 'asc' : 'desc' }
}
// ========== NumberUtils 数字方法 ==========
/**
* 数组求和
*
* @param values 数字数组
* @return 求和结果,默认为 0
*/
export const getSumValue = (values: number[]): number => {
return values.reduce((prev, curr) => {
const value = Number(curr)
if (!Number.isNaN(value)) {
return prev + curr
} else {
return prev
}
}, 0)
}
// ========== 通用金额方法 ==========
/**
* 将一个整数转换为分数保留两位小数
* @param num
*/
export const formatToFraction = (num: number | string | undefined): string => {
if (typeof num === 'undefined') return '0.00'
const parsedNumber = typeof num === 'string' ? parseFloat(num) : num
return (parsedNumber / 100.0).toFixed(2)
}
/**
* 将一个数转换为 1.00 这样
* 数据呈现的时候使用
*
* @param num 整数
*/
// TODO @芋艿:看看怎么融合掉
export const floatToFixed2 = (num: number | string | undefined): string => {
let str = '0.00'
if (typeof num === 'undefined') {
return str
}
const f = formatToFraction(num)
const decimalPart = f.toString().split('.')[1]
const len = decimalPart ? decimalPart.length : 0
switch (len) {
case 0:
str = f.toString() + '.00'
break
case 1:
str = f.toString() + '0'
break
case 2:
str = f.toString()
break
}
return str
}
/**
* 将一个分数转换为整数
* @param num
*/
// TODO @芋艿:看看怎么融合掉
export const convertToInteger = (num: number | string | undefined): number => {
if (typeof num === 'undefined') return 0
const parsedNumber = typeof num === 'string' ? parseFloat(num) : num
// TODO 分转元后还有小数则四舍五入
return Math.round(parsedNumber * 100)
}
/**
* 元转分
*/
export const yuanToFen = (amount: string | number): number => {
return convertToInteger(amount)
}
/**
* 分转元
*/
export const fenToYuan = (price: string | number): string => {
return formatToFraction(price)
}
/**
* 计算环比
*
* @param value 当前数值
* @param reference 对比数值
*/
export const calculateRelativeRate = (value?: number, reference?: number) => {
// 防止除0
if (!reference || reference == 0) return 0
return ((100 * ((value || 0) - reference)) / reference).toFixed(0)
}
// ========== ERP 专属方法 ==========
const ERP_COUNT_DIGIT = 3
const ERP_PRICE_DIGIT = 2
/**
* 【ERP】格式化 Input 数字
*
* 例如说:库存数量
*
* @param num 数量
* @package digit 保留的小数位数
* @return 格式化后的数量
*/
export const erpNumberFormatter = (num: number | string | undefined, digit: number) => {
if (num == null) {
return ''
}
if (typeof num === 'string') {
num = parseFloat(num)
}
// 如果非 number则直接返回空串
if (isNaN(num)) {
return ''
}
return num.toFixed(digit)
}
/**
* 【ERP】格式化数量保留三位小数
*
* 例如说:库存数量
*
* @param num 数量
* @return 格式化后的数量
*/
export const erpCountInputFormatter = (num: number | string | undefined) => {
return erpNumberFormatter(num, ERP_COUNT_DIGIT)
}
// noinspection JSCommentMatchesSignature
/**
* 【ERP】格式化数量保留三位小数
*
* @param cellValue 数量
* @return 格式化后的数量
*/
export const erpCountTableColumnFormatter = (_, __, cellValue: any, ___) => {
return erpNumberFormatter(cellValue, ERP_COUNT_DIGIT)
}
/**
* 【ERP】格式化金额保留二位小数
*
* 例如说:库存数量
*
* @param num 数量
* @return 格式化后的数量
*/
export const erpPriceInputFormatter = (num: number | string | undefined) => {
return erpNumberFormatter(num, ERP_PRICE_DIGIT)
}
// noinspection JSCommentMatchesSignature
/**
* 【ERP】格式化金额保留二位小数
*
* @param cellValue 数量
* @return 格式化后的数量
*/
export const erpPriceTableColumnFormatter = (_, __, cellValue: any, ___) => {
return erpNumberFormatter(cellValue, ERP_PRICE_DIGIT)
}
/**
* 【ERP】价格计算四舍五入保留两位小数
*
* @param price 价格
* @param count 数量
* @return 总价格。如果有任一为空,则返回 undefined
*/
export const erpPriceMultiply = (price: number, count: number) => {
if (price == null || count == null) {
return undefined
}
return parseFloat((price * count).toFixed(ERP_PRICE_DIGIT))
}
/**
* 【ERP】百分比计算四舍五入保留两位小数
*
* 如果 total 为 0则返回 0
*
* @param value 当前值
* @param total 总值
*/
export const erpCalculatePercentage = (value: number, total: number) => {
if (total === 0) return 0
return ((value / total) * 100).toFixed(2)
}
/**
* 适配 echarts map 的地名
*
* @param areaName 地区名称
*/
export const areaReplace = (areaName: string) => {
if (!areaName) {
return areaName
}
return areaName
.replace('维吾尔自治区', '')
.replace('壮族自治区', '')
.replace('回族自治区', '')
.replace('自治区', '')
.replace('省', '')
}
/**
* 解析 JSON 字符串
*
* @param str
*/
export function jsonParse(str: string) {
try {
return JSON.parse(str)
} catch (e) {
console.warn(`str[${str}] 不是一个 JSON 字符串`)
return str
}
}
/**
* 截取字符串
*
* @param str 字符串
* @param start 开始位置
* @param end 结束位置
*/
export const subString = (str: string, start: number, end: number) => {
if (str.length > end) {
return str.slice(start, end)
}
return str
}

118
src/utils/is.ts Normal file
View File

@@ -0,0 +1,118 @@
// copy to vben-admin
const toString = Object.prototype.toString
export const is = (val: unknown, type: string) => {
return toString.call(val) === `[object ${type}]`
}
export const isDef = <T = unknown>(val?: T): val is T => {
return typeof val !== 'undefined'
}
export const isUnDef = <T = unknown>(val?: T): val is T => {
return !isDef(val)
}
export const isObject = (val: any): val is Record<any, any> => {
return val !== null && is(val, 'Object')
}
export const isEmpty = (val: any): boolean => {
if (val === null || val === undefined || typeof val === 'undefined') {
return true
}
if (isArray(val) || isString(val)) {
return val.length === 0
}
if (val instanceof Map || val instanceof Set) {
return val.size === 0
}
if (isObject(val)) {
return Object.keys(val).length === 0
}
return false
}
export const isDate = (val: unknown): val is Date => {
return is(val, 'Date')
}
export const isNull = (val: unknown): val is null => {
return val === null
}
export const isNullAndUnDef = (val: unknown): val is null | undefined => {
return isUnDef(val) && isNull(val)
}
export const isNullOrUnDef = (val: unknown): val is null | undefined => {
return isUnDef(val) || isNull(val)
}
export const isNumber = (val: unknown): val is number => {
return is(val, 'Number')
}
export const isPromise = <T = any>(val: unknown): val is Promise<T> => {
return is(val, 'Promise') && isObject(val) && isFunction(val.then) && isFunction(val.catch)
}
export const isString = (val: unknown): val is string => {
return is(val, 'String')
}
export const isFunction = (val: unknown): val is Function => {
return typeof val === 'function'
}
export const isBoolean = (val: unknown): val is boolean => {
return is(val, 'Boolean')
}
export const isRegExp = (val: unknown): val is RegExp => {
return is(val, 'RegExp')
}
export const isArray = (val: any): val is Array<any> => {
return val && Array.isArray(val)
}
export const isWindow = (val: any): val is Window => {
return typeof window !== 'undefined' && is(val, 'Window')
}
export const isElement = (val: unknown): val is Element => {
return isObject(val) && !!val.tagName
}
export const isMap = (val: unknown): val is Map<any, any> => {
return is(val, 'Map')
}
export const isServer = typeof window === 'undefined'
export const isClient = !isServer
export const isUrl = (path: string): boolean => {
// fix:修复hash路由无法跳转的问题
const reg =
/(((^https?:(?:\/\/)?)(?:[-:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%#\/.\w-_]*)?\??(?:[-\+=&%@.\w_]*)#?(?:[\w]*))?)$/
return reg.test(path)
}
export const isDark = (): boolean => {
return window.matchMedia('(prefers-color-scheme: dark)').matches
}
// 是否是图片链接
export const isImgPath = (path: string): boolean => {
return /(https?:\/\/|data:image\/).*?\.(png|jpg|jpeg|gif|svg|webp|ico)/gi.test(path)
}
export const isEmptyVal = (val: any): boolean => {
return val === '' || val === null || val === undefined
}

31
src/utils/jsencrypt.ts Normal file
View File

@@ -0,0 +1,31 @@
import { JSEncrypt } from 'jsencrypt'
// 密钥对生成 http://web.chacuo.net/netrsakeypair
const publicKey =
'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKoR8mX0rGKLqzcWmOzbfj64K8ZIgOdH\n' +
'nzkXSOVOZbFu/TJhZ7rFAN+eaGkl3C4buccQd/EjEsj9ir7ijT7h96MCAwEAAQ=='
const privateKey =
'MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAqhHyZfSsYourNxaY\n' +
'7Nt+PrgrxkiA50efORdI5U5lsW79MmFnusUA355oaSXcLhu5xxB38SMSyP2KvuKN\n' +
'PuH3owIDAQABAkAfoiLyL+Z4lf4Myxk6xUDgLaWGximj20CUf+5BKKnlrK+Ed8gA\n' +
'kM0HqoTt2UZwA5E2MzS4EI2gjfQhz5X28uqxAiEA3wNFxfrCZlSZHb0gn2zDpWow\n' +
'cSxQAgiCstxGUoOqlW8CIQDDOerGKH5OmCJ4Z21v+F25WaHYPxCFMvwxpcw99Ecv\n' +
'DQIgIdhDTIqD2jfYjPTY8Jj3EDGPbH2HHuffvflECt3Ek60CIQCFRlCkHpi7hthh\n' +
'YhovyloRYsM+IS9h/0BzlEAuO0ktMQIgSPT3aFAgJYwKpqRYKlLDVcflZFCKY7u3\n' +
'UP8iWi1Qw0Y='
// 加密
export const encrypt = (txt: string) => {
const encryptor = new JSEncrypt()
encryptor.setPublicKey(publicKey) // 设置公钥
return encryptor.encrypt(txt) // 对数据进行加密
}
// 解密
export const decrypt = (txt: string) => {
const encryptor = new JSEncrypt()
encryptor.setPrivateKey(privateKey) // 设置私钥
return encryptor.decrypt(txt) // 对数据进行解密
}

36
src/utils/permission.ts Normal file
View File

@@ -0,0 +1,36 @@
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import {hasPermission} from "@/directives/permission/hasPermi";
const { t } = useI18n() // 国际化
/**
* 字符权限校验
* @param {Array} value 校验值
* @returns {Boolean}
*/
export function checkPermi(permission: string[]) {
return hasPermission(permission)
}
/**
* 角色权限校验
* @param {string[]} value 校验值
* @returns {Boolean}
*/
export function checkRole(value: string[]) {
if (value && value instanceof Array && value.length > 0) {
const { wsCache } = useCache()
const permissionRoles = value
const super_admin = 'super_admin'
const userInfo = wsCache.get(CACHE_KEY.USER)
const roles = userInfo?.roles || []
const hasRole = roles.some((role: string) => {
return super_admin === role || permissionRoles.includes(role)
})
return !!hasRole
} else {
console.error(t('permission.hasRole'))
return false
}
}

24
src/utils/propTypes.ts Normal file
View File

@@ -0,0 +1,24 @@
import { VueTypeValidableDef, VueTypesInterface, createTypes, toValidableType } from 'vue-types'
import { CSSProperties } from 'vue'
type PropTypes = VueTypesInterface & {
readonly style: VueTypeValidableDef<CSSProperties>
}
const newPropTypes = createTypes({
func: undefined,
bool: undefined,
string: undefined,
number: undefined,
object: undefined,
integer: undefined
}) as PropTypes
class propTypes extends newPropTypes {
static get style() {
return toValidableType('style', {
type: [String, Object]
})
}
}
export { propTypes }

256
src/utils/routerHelper.ts Normal file
View File

@@ -0,0 +1,256 @@
import type { RouteLocationNormalized, Router, RouteRecordNormalized } from 'vue-router'
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import { isUrl } from '@/utils/is'
import { cloneDeep, omit } from 'lodash-es'
import qs from 'qs'
const modules = import.meta.glob('../views/**/*.{vue,tsx}')
/**
* 注册一个异步组件
* @param componentPath 例:/bpm/oa/leave/detail
*/
export const registerComponent = (componentPath: string) => {
for (const item in modules) {
if (item.includes(componentPath)) {
// 使用异步组件的方式来动态加载组件
// @ts-ignore
return defineAsyncComponent(modules[item])
}
}
}
/* Layout */
export const Layout = () => import('@/layout/Layout.vue')
export const getParentLayout = () => {
return () =>
new Promise((resolve) => {
resolve({
name: 'ParentLayout'
})
})
}
// 按照路由中meta下的rank等级升序来排序路由
export const ascending = (arr: any[]) => {
arr.forEach((v) => {
if (v?.meta?.rank === null) v.meta.rank = undefined
if (v?.meta?.rank === 0) {
if (v.name !== 'home' && v.path !== '/') {
console.warn('rank only the home page can be 0')
}
}
})
return arr.sort((a: { meta: { rank: number } }, b: { meta: { rank: number } }) => {
return a?.meta?.rank - b?.meta?.rank
})
}
export const getRawRoute = (route: RouteLocationNormalized): RouteLocationNormalized => {
if (!route) return route
const { matched, ...opt } = route
return {
...opt,
matched: (matched
? matched.map((item) => ({
meta: item.meta,
name: item.name,
path: item.path
}))
: undefined) as RouteRecordNormalized[]
}
}
// 后端控制路由生成
export const generateRoute = (routes: AppCustomRouteRecordRaw[]): AppRouteRecordRaw[] => {
const res: AppRouteRecordRaw[] = []
const modulesRoutesKeys = Object.keys(modules)
for (const route of routes) {
// 1. 生成 meta 菜单元数据
const meta = {
title: route.name,
icon: route.icon,
hidden: !route.visible,
noCache: !route.keepAlive,
alwaysShow:
route.children &&
route.children.length > 0 &&
(route.alwaysShow !== undefined ? route.alwaysShow : true)
} as any
// 特殊逻辑:如果后端配置的 MenuDO.component 包含 ?,则表示需要传递参数
// 此时,我们需要解析参数,并且将参数放到 meta.query 中
// 这样,后续在 Vue 文件中,可以通过 const { currentRoute } = useRouter() 中,通过 meta.query 获取到参数
if (route.component && route.component.indexOf('?') > -1) {
const query = route.component.split('?')[1]
route.component = route.component.split('?')[0]
meta.query = qs.parse(query)
}
// 2. 生成 dataAppRouteRecordRaw
// 路由地址转首字母大写驼峰作为路由名称适配keepAlive
let data: AppRouteRecordRaw = {
path:
route.path.indexOf('?') > -1 && !isUrl(route.path) ? route.path.split('?')[0] : route.path, // 注意,需要排除 http 这种 url避免它带 ? 参数被截取掉
name:
route.componentName && route.componentName.length > 0
? route.componentName
: toCamelCase(route.path, true),
redirect: route.redirect,
meta: meta
}
//处理顶级非目录路由
if (!route.children && route.parentId == 0 && route.component) {
data.component = Layout
data.meta = {
hidden: meta.hidden,
}
data.name = toCamelCase(route.path, true) + 'Parent'
data.redirect = ''
meta.alwaysShow = true
const childrenData: AppRouteRecordRaw = {
path: '',
name:
route.componentName && route.componentName.length > 0
? route.componentName
: toCamelCase(route.path, true),
redirect: route.redirect,
meta: meta
}
const index = route?.component
? modulesRoutesKeys.findIndex((ev) => ev.includes(route.component))
: modulesRoutesKeys.findIndex((ev) => ev.includes(route.path))
childrenData.component = modules[modulesRoutesKeys[index]]
data.children = [childrenData]
} else {
// 目录
if (route.children?.length) {
data.component = Layout
data.redirect = getRedirect(route.path, route.children)
// 外链
} else if (isUrl(route.path)) {
data = {
path: '/external-link',
component: Layout,
meta: {
name: route.name
},
children: [data]
} as AppRouteRecordRaw
// 菜单
} else {
// 对后端传component组件路径和不传做兼容如果后端传component组件路径那么path可以随便写如果不传component组件路径会根path保持一致
const index = route?.component
? modulesRoutesKeys.findIndex((ev) => ev.includes(route.component))
: modulesRoutesKeys.findIndex((ev) => ev.includes(route.path))
data.component = modules[modulesRoutesKeys[index]]
}
if (route.children) {
data.children = generateRoute(route.children)
}
}
res.push(data as AppRouteRecordRaw)
}
return res
}
export const getRedirect = (parentPath: string, children: AppCustomRouteRecordRaw[]) => {
if (!children || children.length == 0) {
return parentPath
}
const path = generateRoutePath(parentPath, children[0].path)
// 递归子节点
if (children[0].children) return getRedirect(path, children[0].children)
}
const generateRoutePath = (parentPath: string, path: string) => {
if (parentPath.endsWith('/')) {
parentPath = parentPath.slice(0, -1) // 移除默认的 /
}
if (!path.startsWith('/')) {
path = '/' + path
}
return parentPath + path
}
export const pathResolve = (parentPath: string, path: string) => {
if (isUrl(path)) return path
const childPath = path.startsWith('/') || !path ? path : `/${path}`
return `${parentPath}${childPath}`.replace(/\/\//g, '/')
}
// 路由降级
export const flatMultiLevelRoutes = (routes: AppRouteRecordRaw[]) => {
const modules: AppRouteRecordRaw[] = cloneDeep(routes)
for (let index = 0; index < modules.length; index++) {
const route = modules[index]
if (!isMultipleRoute(route)) {
continue
}
promoteRouteLevel(route)
}
return modules
}
// 层级是否大于2
const isMultipleRoute = (route: AppRouteRecordRaw) => {
if (!route || !Reflect.has(route, 'children') || !route.children?.length) {
return false
}
const children = route.children
let flag = false
for (let index = 0; index < children.length; index++) {
const child = children[index]
if (child.children?.length) {
flag = true
break
}
}
return flag
}
// 生成二级路由
const promoteRouteLevel = (route: AppRouteRecordRaw) => {
let router: Router | null = createRouter({
routes: [route as RouteRecordRaw],
history: createWebHashHistory()
})
const routes = router.getRoutes()
addToChildren(routes, route.children || [], route)
router = null
route.children = route.children?.map((item) => omit(item, 'children'))
}
// 添加所有子菜单
const addToChildren = (
routes: RouteRecordNormalized[],
children: AppRouteRecordRaw[],
routeModule: AppRouteRecordRaw
) => {
for (let index = 0; index < children.length; index++) {
const child = children[index]
const route = routes.find((item) => item.name === child.name)
if (!route) {
continue
}
routeModule.children = routeModule.children || []
if (!routeModule.children.find((item) => item.name === route.name)) {
routeModule.children?.push(route as unknown as AppRouteRecordRaw)
}
if (child.children?.length) {
addToChildren(routes, child.children, routeModule)
}
}
}
const toCamelCase = (str: string, upperCaseFirst: boolean) => {
str = (str || '')
.replace(/-(.)/g, function (group1: string) {
return group1.toUpperCase()
})
.replaceAll('-', '')
if (upperCaseFirst && str) {
str = str.charAt(0).toUpperCase() + str.slice(1)
}
return str
}

403
src/utils/tree.ts Normal file
View File

@@ -0,0 +1,403 @@
interface TreeHelperConfig {
id: string
children: string
pid: string
}
const DEFAULT_CONFIG: TreeHelperConfig = {
id: 'id',
children: 'children',
pid: 'pid'
}
export const defaultProps = {
children: 'children',
label: 'name',
value: 'id',
isLeaf: 'leaf',
emitPath: false // 用于 cascader 组件:在选中节点改变时,是否返回由该节点所在的各级菜单的值所组成的数组,若设置 false则只返回该节点的值
}
const getConfig = (config: Partial<TreeHelperConfig>) => Object.assign({}, DEFAULT_CONFIG, config)
// tree from list
export const listToTree = <T = any>(list: any[], config: Partial<TreeHelperConfig> = {}): T[] => {
const conf = getConfig(config) as TreeHelperConfig
const nodeMap = new Map()
const result: T[] = []
const { id, children, pid } = conf
for (const node of list) {
node[children] = node[children] || []
nodeMap.set(node[id], node)
}
for (const node of list) {
const parent = nodeMap.get(node[pid])
;(parent ? parent.children : result).push(node)
}
return result
}
export const treeToList = <T = any>(tree: any, config: Partial<TreeHelperConfig> = {}): T => {
config = getConfig(config)
const { children } = config
const result: any = [...tree]
for (let i = 0; i < result.length; i++) {
if (!result[i][children!]) continue
result.splice(i + 1, 0, ...result[i][children!])
}
return result
}
export const findNode = <T = any>(
tree: any,
func: Fn,
config: Partial<TreeHelperConfig> = {}
): T | null => {
config = getConfig(config)
const { children } = config
const list = [...tree]
for (const node of list) {
if (func(node)) return node
node[children!] && list.push(...node[children!])
}
return null
}
export const findNodeAll = <T = any>(
tree: any,
func: Fn,
config: Partial<TreeHelperConfig> = {}
): T[] => {
config = getConfig(config)
const { children } = config
const list = [...tree]
const result: T[] = []
for (const node of list) {
func(node) && result.push(node)
node[children!] && list.push(...node[children!])
}
return result
}
export const findPath = <T = any>(
tree: any,
func: Fn,
config: Partial<TreeHelperConfig> = {}
): T | T[] | null => {
config = getConfig(config)
const path: T[] = []
const list = [...tree]
const visitedSet = new Set()
const { children } = config
while (list.length) {
const node = list[0]
if (visitedSet.has(node)) {
path.pop()
list.shift()
} else {
visitedSet.add(node)
node[children!] && list.unshift(...node[children!])
path.push(node)
if (func(node)) {
return path
}
}
}
return null
}
export const findPathAll = (tree: any, func: Fn, config: Partial<TreeHelperConfig> = {}) => {
config = getConfig(config)
const path: any[] = []
const list = [...tree]
const result: any[] = []
const visitedSet = new Set(),
{ children } = config
while (list.length) {
const node = list[0]
if (visitedSet.has(node)) {
path.pop()
list.shift()
} else {
visitedSet.add(node)
node[children!] && list.unshift(...node[children!])
path.push(node)
func(node) && result.push([...path])
}
}
return result
}
export const filter = <T = any>(
tree: T[],
func: (n: T) => boolean,
config: Partial<TreeHelperConfig> = {}
): T[] => {
config = getConfig(config)
const children = config.children as string
function listFilter(list: T[]) {
return list
.map((node: any) => ({ ...node }))
.filter((node) => {
node[children] = node[children] && listFilter(node[children])
return func(node) || (node[children] && node[children].length)
})
}
return listFilter(tree)
}
export const forEach = <T = any>(
tree: T[],
func: (n: T) => any,
config: Partial<TreeHelperConfig> = {}
): void => {
config = getConfig(config)
const list: any[] = [...tree]
const { children } = config
for (let i = 0; i < list.length; i++) {
// func 返回true就终止遍历避免大量节点场景下无意义循环引起浏览器卡顿
if (func(list[i])) {
return
}
children && list[i][children] && list.splice(i + 1, 0, ...list[i][children])
}
}
/**
* @description: Extract tree specified structure
*/
export const treeMap = <T = any>(
treeData: T[],
opt: { children?: string; conversion: Fn }
): T[] => {
return treeData.map((item) => treeMapEach(item, opt))
}
/**
* @description: Extract tree specified structure
*/
export const treeMapEach = (
data: any,
{ children = 'children', conversion }: { children?: string; conversion: Fn }
) => {
const haveChildren = Array.isArray(data[children]) && data[children].length > 0
const conversionData = conversion(data) || {}
if (haveChildren) {
return {
...conversionData,
[children]: data[children].map((i: number) =>
treeMapEach(i, {
children,
conversion
})
)
}
} else {
return {
...conversionData
}
}
}
/**
* 递归遍历树结构
* @param treeDatas 树
* @param callBack 回调
* @param parentNode 父节点
*/
export const eachTree = (treeDatas: any[], callBack: Fn, parentNode = {}) => {
treeDatas.forEach((element) => {
const newNode = callBack(element, parentNode) || element
if (element.children) {
eachTree(element.children, callBack, newNode)
}
})
}
/**
* 构造树型结构数据
* @param {*} data 数据源
* @param {*} id id字段 默认 'id'
* @param {*} parentId 父节点字段 默认 'parentId'
* @param {*} children 孩子节点字段 默认 'children'
*/
export const handleTree = (data: any[], id?: string, parentId?: string, children?: string) => {
if (!Array.isArray(data)) {
console.warn('data must be an array')
return []
}
const config = {
id: id || 'id',
parentId: parentId || 'parentId',
childrenList: children || 'children'
}
const childrenListMap = {}
const nodeIds = {}
const tree: any[] = []
for (const d of data) {
const parentId = d[config.parentId]
if (childrenListMap[parentId] == null) {
childrenListMap[parentId] = []
}
nodeIds[d[config.id]] = d
childrenListMap[parentId].push(d)
}
for (const d of data) {
const parentId = d[config.parentId]
if (nodeIds[parentId] == null) {
tree.push(d)
}
}
for (const t of tree) {
adaptToChildrenList(t)
}
function adaptToChildrenList(o) {
if (childrenListMap[o[config.id]] !== null) {
o[config.childrenList] = childrenListMap[o[config.id]]
}
if (o[config.childrenList]) {
for (const c of o[config.childrenList]) {
adaptToChildrenList(c)
}
}
}
return tree
}
/**
* 构造树型结构数据
* @param {*} data 数据源
* @param {*} id id字段 默认 'id'
* @param {*} parentId 父节点字段 默认 'parentId'
* @param {*} children 孩子节点字段 默认 'children'
* @param {*} rootId 根Id 默认 0
*/
// @ts-ignore
export const handleTree2 = (data, id, parentId, children, rootId) => {
id = id || 'id'
parentId = parentId || 'parentId'
// children = children || 'children'
rootId =
rootId ||
Math.min(
...data.map((item) => {
return item[parentId]
})
) ||
0
// 对源数据深度克隆
const cloneData = JSON.parse(JSON.stringify(data))
// 循环所有项
const treeData = cloneData.filter((father) => {
const branchArr = cloneData.filter((child) => {
// 返回每一项的子级数组
return father[id] === child[parentId]
})
branchArr.length > 0 ? (father.children = branchArr) : ''
// 返回第一层
return father[parentId] === rootId
})
return treeData !== '' ? treeData : data
}
/**
* 校验选中的节点,是否为指定 level
*
* @param tree 要操作的树结构数据
* @param nodeId 需要判断在什么层级的数据
* @param level 检查的级别, 默认检查到二级
* @return true 是false 否
*/
export const checkSelectedNode = (tree: any[], nodeId: any, level = 2): boolean => {
if (typeof tree === 'undefined' || !Array.isArray(tree) || tree.length === 0) {
console.warn('tree must be an array')
return false
}
// 校验是否是一级节点
if (tree.some((item) => item.id === nodeId)) {
return false
}
// 递归计数
let count = 1
// 深层次校验
function performAThoroughValidation(arr: any[]): boolean {
count += 1
for (const item of arr) {
if (item.id === nodeId) {
return true
} else if (typeof item.children !== 'undefined' && item.children.length !== 0) {
if (performAThoroughValidation(item.children)) {
return true
}
}
}
return false
}
for (const item of tree) {
count = 1
if (performAThoroughValidation(item.children)) {
// 找到后对比是否是期望的层级
if (count >= level) {
return true
}
}
}
return false
}
/**
* 获取节点的完整结构
* @param tree 树数据
* @param nodeId 节点 id
*/
export const treeToString = (tree: any[], nodeId) => {
if (typeof tree === 'undefined' || !Array.isArray(tree) || tree.length === 0) {
console.warn('tree must be an array')
return ''
}
// 校验是否是一级节点
const node = tree.find((item) => item.id === nodeId)
if (typeof node !== 'undefined') {
return node.name
}
let str = ''
function performAThoroughValidation(arr) {
if (typeof arr === 'undefined' || !Array.isArray(arr) || arr.length === 0) {
return false
}
for (const item of arr) {
if (item.id === nodeId) {
str += ` / ${item.name}`
return true
} else if (typeof item.children !== 'undefined' && item.children.length !== 0) {
str += ` / ${item.name}`
if (performAThoroughValidation(item.children)) {
return true
}
}
}
return false
}
for (const item of tree) {
str = `${item.name}`
if (performAThoroughValidation(item.children)) {
break
}
}
return str
}

16
src/utils/tsxHelper.ts Normal file
View File

@@ -0,0 +1,16 @@
import { Slots } from 'vue'
import { isFunction } from '@/utils/is'
export const getSlot = (slots: Slots, slot = 'default', data?: Recordable) => {
// Reflect.has 判断一个对象是否存在某个属性
if (!slots || !Reflect.has(slots, slot)) {
return null
}
if (!isFunction(slots[slot])) {
console.error(`${slot} is not a function!`)
return null
}
const slotFn = slots[slot]
if (!slotFn) return null
return slotFn(data)
}