新增
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
import { TOKEN_KEY } from '@/enums/cacheEnums'
|
||||
import { resetRouter } from '@/router'
|
||||
import useTabsStore from '@/stores/modules/multipleTabs'
|
||||
import useUserStore from '@/stores/modules/user'
|
||||
|
||||
import cache from './cache'
|
||||
|
||||
export function getToken() {
|
||||
return cache.get(TOKEN_KEY)
|
||||
}
|
||||
|
||||
export function clearAuthInfo() {
|
||||
const userStore = useUserStore()
|
||||
const tabsStore = useTabsStore()
|
||||
userStore.resetState()
|
||||
tabsStore.resetState()
|
||||
cache.remove(TOKEN_KEY)
|
||||
resetRouter()
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
const cache = {
|
||||
key: 'like_admin_',
|
||||
//设置缓存(expire为缓存时效)
|
||||
set(key: string, value: any, expire?: string) {
|
||||
key = this.getKey(key)
|
||||
let data: any = {
|
||||
expire: expire ? this.time() + expire : '',
|
||||
value
|
||||
}
|
||||
|
||||
if (typeof data === 'object') {
|
||||
data = JSON.stringify(data)
|
||||
}
|
||||
try {
|
||||
window.localStorage.setItem(key, data)
|
||||
} catch (e) {
|
||||
return null
|
||||
}
|
||||
},
|
||||
get(key: string) {
|
||||
key = this.getKey(key)
|
||||
try {
|
||||
const data = window.localStorage.getItem(key)
|
||||
if (!data) {
|
||||
return null
|
||||
}
|
||||
const { value, expire } = JSON.parse(data)
|
||||
if (expire && expire < this.time()) {
|
||||
window.localStorage.removeItem(key)
|
||||
return null
|
||||
}
|
||||
return value
|
||||
} catch (e) {
|
||||
return null
|
||||
}
|
||||
},
|
||||
//获取当前时间
|
||||
time() {
|
||||
return Math.round(new Date().getTime() / 1000)
|
||||
},
|
||||
remove(key: string) {
|
||||
key = this.getKey(key)
|
||||
window.localStorage.removeItem(key)
|
||||
},
|
||||
clear() {
|
||||
window.localStorage.clear()
|
||||
},
|
||||
getKey(key: string) {
|
||||
return this.key + key
|
||||
}
|
||||
}
|
||||
|
||||
export default cache
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* @description: 开发模式
|
||||
*/
|
||||
export function isDevMode(): boolean {
|
||||
return import.meta.env.DEV
|
||||
}
|
||||
|
||||
/**
|
||||
* @description: 生成模式
|
||||
*/
|
||||
export function isProdMode(): boolean {
|
||||
return import.meta.env.PROD
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import {
|
||||
ElLoading,
|
||||
ElMessage,
|
||||
ElMessageBox,
|
||||
type ElMessageBoxOptions,
|
||||
ElNotification
|
||||
} from 'element-plus'
|
||||
import type { LoadingInstance } from 'element-plus/es/components/loading/src/loading'
|
||||
|
||||
export class Feedback {
|
||||
private loadingInstance: LoadingInstance | null = null
|
||||
static instance: Feedback | null = null
|
||||
static getInstance() {
|
||||
return this.instance ?? (this.instance = new Feedback())
|
||||
}
|
||||
// 消息提示
|
||||
msg(msg: string) {
|
||||
ElMessage.info(msg)
|
||||
}
|
||||
// 错误消息
|
||||
msgError(msg: string) {
|
||||
ElMessage.error(msg)
|
||||
}
|
||||
// 成功消息
|
||||
msgSuccess(msg: string) {
|
||||
ElMessage.success(msg)
|
||||
}
|
||||
// 警告消息
|
||||
msgWarning(msg: string) {
|
||||
ElMessage.warning(msg)
|
||||
}
|
||||
// 弹出提示
|
||||
alert(msg: string) {
|
||||
ElMessageBox.alert(msg, '系统提示')
|
||||
}
|
||||
// 错误提示
|
||||
alertError(msg: string) {
|
||||
ElMessageBox.alert(msg, '系统提示', { type: 'error' })
|
||||
}
|
||||
// 成功提示
|
||||
alertSuccess(msg: string) {
|
||||
ElMessageBox.alert(msg, '系统提示', { type: 'success' })
|
||||
}
|
||||
// 警告提示
|
||||
alertWarning(msg: string) {
|
||||
ElMessageBox.alert(msg, '系统提示', { type: 'warning' })
|
||||
}
|
||||
// 通知提示
|
||||
notify(msg: string) {
|
||||
ElNotification.info(msg)
|
||||
}
|
||||
// 错误通知
|
||||
notifyError(msg: string) {
|
||||
ElNotification.error(msg)
|
||||
}
|
||||
// 成功通知
|
||||
notifySuccess(msg: string) {
|
||||
ElNotification.success(msg)
|
||||
}
|
||||
// 警告通知
|
||||
notifyWarning(msg: string) {
|
||||
ElNotification.warning(msg)
|
||||
}
|
||||
// 确认窗体
|
||||
confirm(msg: string) {
|
||||
return ElMessageBox.confirm(msg, '温馨提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning'
|
||||
})
|
||||
}
|
||||
// 提交内容
|
||||
prompt(content: string, title: string, options?: ElMessageBoxOptions) {
|
||||
return ElMessageBox.prompt(content, title, {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
...options
|
||||
})
|
||||
}
|
||||
// 打开全局loading
|
||||
loading(msg: string) {
|
||||
this.loadingInstance = ElLoading.service({
|
||||
lock: true,
|
||||
text: msg
|
||||
})
|
||||
}
|
||||
// 关闭全局loading
|
||||
closeLoading() {
|
||||
this.loadingInstance?.close()
|
||||
}
|
||||
}
|
||||
|
||||
const feedback = Feedback.getInstance()
|
||||
|
||||
export default feedback
|
||||
@@ -0,0 +1,11 @@
|
||||
import { ref } from 'vue'
|
||||
|
||||
/**
|
||||
* 组件类型标注
|
||||
* @param _component 组件实例
|
||||
* @returns 完整类型标注的响应式组件实例
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
export const useComponentRef = <T extends abstract new (...args: any) => any>(_component: T) => {
|
||||
return ref<InstanceType<T>>()
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import useUserStore from '@/stores/modules/user'
|
||||
|
||||
export const hasPermission = (perms: string[]): boolean => {
|
||||
const userStore = useUserStore()
|
||||
const permissions = userStore.perms
|
||||
const all_permission = '*'
|
||||
if (perms.length > 0) {
|
||||
let hasPermission = true
|
||||
perms.forEach((key: string) => {
|
||||
if (!permissions.includes(key) && !permissions.includes(all_permission)) {
|
||||
hasPermission = false
|
||||
}
|
||||
})
|
||||
return hasPermission
|
||||
} else {
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import axios, {
|
||||
AxiosError,
|
||||
type AxiosInstance,
|
||||
type AxiosRequestConfig,
|
||||
type AxiosResponse,
|
||||
type InternalAxiosRequestConfig
|
||||
} from 'axios'
|
||||
import { cloneDeep, isFunction, merge } from 'lodash'
|
||||
|
||||
import { RequestMethodsEnum } from '@/enums/requestEnums'
|
||||
|
||||
import axiosCancel from './cancel'
|
||||
import type { RequestData, RequestOptions } from './type'
|
||||
|
||||
export class Axios {
|
||||
private axiosInstance: AxiosInstance
|
||||
private readonly config: AxiosRequestConfig
|
||||
private readonly options: RequestOptions
|
||||
constructor(config: AxiosRequestConfig) {
|
||||
this.config = config
|
||||
this.options = config.requestOptions
|
||||
this.axiosInstance = axios.create(config)
|
||||
this.setupInterceptors()
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 获取axios实例
|
||||
*/
|
||||
getAxiosInstance() {
|
||||
return this.axiosInstance
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 设置拦截器
|
||||
*/
|
||||
setupInterceptors() {
|
||||
if (!this.config.axiosHooks) {
|
||||
return
|
||||
}
|
||||
const {
|
||||
requestInterceptorsHook,
|
||||
requestInterceptorsCatchHook,
|
||||
responseInterceptorsHook,
|
||||
responseInterceptorsCatchHook
|
||||
} = this.config.axiosHooks
|
||||
this.axiosInstance.interceptors.request.use(
|
||||
(config) => {
|
||||
this.addCancelToken(config)
|
||||
if (isFunction(requestInterceptorsHook)) {
|
||||
config = requestInterceptorsHook(config) as InternalAxiosRequestConfig
|
||||
}
|
||||
return config
|
||||
},
|
||||
(err: Error) => {
|
||||
if (isFunction(requestInterceptorsCatchHook)) {
|
||||
requestInterceptorsCatchHook(err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
)
|
||||
this.axiosInstance.interceptors.response.use(
|
||||
(response: AxiosResponse<RequestData>) => {
|
||||
this.removeCancelToken(response.config.url!)
|
||||
if (isFunction(responseInterceptorsHook)) {
|
||||
response = responseInterceptorsHook(response)
|
||||
}
|
||||
return response
|
||||
},
|
||||
(err: AxiosError) => {
|
||||
if (isFunction(responseInterceptorsCatchHook)) {
|
||||
responseInterceptorsCatchHook(err)
|
||||
}
|
||||
if (err.code != AxiosError.ERR_CANCELED) {
|
||||
this.removeCancelToken(err.config?.url!)
|
||||
}
|
||||
|
||||
if (err.code == AxiosError.ECONNABORTED || err.code == AxiosError.ERR_NETWORK) {
|
||||
return new Promise((resolve) => setTimeout(resolve, 500)).then(() =>
|
||||
this.retryRequest(err)
|
||||
)
|
||||
}
|
||||
return Promise.reject(err)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 添加CancelToken
|
||||
*/
|
||||
addCancelToken(config: AxiosRequestConfig) {
|
||||
const { ignoreCancelToken } = config.requestOptions
|
||||
!ignoreCancelToken && axiosCancel.add(config)
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 移除CancelToken
|
||||
*/
|
||||
removeCancelToken(url: string) {
|
||||
axiosCancel.remove(url)
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 重新请求
|
||||
*/
|
||||
retryRequest(error: AxiosError) {
|
||||
const config = error.config as any
|
||||
const { retryCount, isOpenRetry } = config.requestOptions
|
||||
if (!isOpenRetry || config.method?.toUpperCase() == RequestMethodsEnum.POST) {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
config.retryCount = config.retryCount ?? 0
|
||||
|
||||
if (config.retryCount >= retryCount) {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
config.retryCount++
|
||||
|
||||
return this.axiosInstance.request(config)
|
||||
}
|
||||
/**
|
||||
* @description get请求
|
||||
*/
|
||||
get<T = any>(
|
||||
config: Partial<AxiosRequestConfig>,
|
||||
options?: Partial<RequestOptions>
|
||||
): Promise<T> {
|
||||
return this.request({ ...config, method: RequestMethodsEnum.GET }, options)
|
||||
}
|
||||
|
||||
/**
|
||||
* @description post请求
|
||||
*/
|
||||
post<T = any>(
|
||||
config: Partial<AxiosRequestConfig>,
|
||||
options?: Partial<RequestOptions>
|
||||
): Promise<T> {
|
||||
return this.request({ ...config, method: RequestMethodsEnum.POST }, options)
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 请求函数
|
||||
*/
|
||||
request<T = any>(
|
||||
config: Partial<AxiosRequestConfig>,
|
||||
options?: Partial<RequestOptions>
|
||||
): Promise<any> {
|
||||
const opt: RequestOptions = merge({}, this.options, options)
|
||||
const axioxConfig: AxiosRequestConfig = {
|
||||
...cloneDeep(config),
|
||||
requestOptions: opt
|
||||
}
|
||||
const { urlPrefix } = opt
|
||||
// 拼接请求前缀如api
|
||||
if (urlPrefix) {
|
||||
axioxConfig.url = `${urlPrefix}${config.url}`
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
this.axiosInstance
|
||||
.request<any, AxiosResponse<RequestData<T>>>(axioxConfig)
|
||||
.then((res) => {
|
||||
resolve(res)
|
||||
})
|
||||
.catch((err) => {
|
||||
reject(err)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import axios, { type AxiosRequestConfig, type Canceler } from 'axios'
|
||||
|
||||
const cancelerMap = new Map<string, Canceler>()
|
||||
|
||||
// 获取一个唯一的请求键,它由请求的 URL 和参数组成
|
||||
function getRequestKey(config: AxiosRequestConfig): string {
|
||||
const { url, method, params, data } = config
|
||||
return [method, url, JSON.stringify(params), JSON.stringify(data)].join('&')
|
||||
}
|
||||
|
||||
export class AxiosCancel {
|
||||
private static instance?: AxiosCancel
|
||||
|
||||
static createInstance() {
|
||||
return this.instance ?? (this.instance = new AxiosCancel())
|
||||
}
|
||||
add(config: AxiosRequestConfig) {
|
||||
const requestKey = getRequestKey(config)
|
||||
this.remove(requestKey)
|
||||
config.cancelToken = new axios.CancelToken((cancel) => {
|
||||
if (!cancelerMap.has(requestKey)) {
|
||||
cancelerMap.set(requestKey, cancel)
|
||||
}
|
||||
})
|
||||
}
|
||||
remove(requestKey: string) {
|
||||
if (cancelerMap.has(requestKey)) {
|
||||
const cancel = cancelerMap.get(requestKey)
|
||||
cancel && cancel(requestKey)
|
||||
cancelerMap.delete(requestKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const axiosCancel = AxiosCancel.createInstance()
|
||||
|
||||
export default axiosCancel
|
||||
@@ -0,0 +1,128 @@
|
||||
import { AxiosError, type AxiosRequestConfig } from 'axios'
|
||||
import { merge } from 'lodash'
|
||||
import NProgress from 'nprogress'
|
||||
|
||||
import configs from '@/config'
|
||||
import { PageEnum } from '@/enums/pageEnum'
|
||||
import { ContentTypeEnum, RequestCodeEnum, RequestMethodsEnum } from '@/enums/requestEnums'
|
||||
import router from '@/router'
|
||||
|
||||
import { clearAuthInfo, getToken } from '../auth'
|
||||
import feedback from '../feedback'
|
||||
import { Axios } from './axios'
|
||||
import type { AxiosHooks } from './type'
|
||||
|
||||
// 处理axios的钩子函数
|
||||
const axiosHooks: AxiosHooks = {
|
||||
requestInterceptorsHook(config) {
|
||||
NProgress.start()
|
||||
const { withToken, isParamsToData } = config.requestOptions
|
||||
const params = config.params || {}
|
||||
const headers = config.headers || {}
|
||||
|
||||
// 添加token
|
||||
if (withToken) {
|
||||
const token = getToken()
|
||||
headers.token = token
|
||||
}
|
||||
// POST请求下如果无data,则将params视为data
|
||||
if (
|
||||
isParamsToData &&
|
||||
!Reflect.has(config, 'data') &&
|
||||
config.method?.toUpperCase() === RequestMethodsEnum.POST
|
||||
) {
|
||||
config.data = params
|
||||
config.params = {}
|
||||
}
|
||||
config.headers = headers
|
||||
return config
|
||||
},
|
||||
requestInterceptorsCatchHook(err) {
|
||||
NProgress.done()
|
||||
return err
|
||||
},
|
||||
async responseInterceptorsHook(response) {
|
||||
NProgress.done()
|
||||
const { isTransformResponse, isReturnDefaultResponse } = response.config.requestOptions
|
||||
|
||||
//返回默认响应,当需要获取响应头及其他数据时可使用
|
||||
if (isReturnDefaultResponse) {
|
||||
return response
|
||||
}
|
||||
// 是否需要对数据进行处理
|
||||
if (!isTransformResponse) {
|
||||
return response.data
|
||||
}
|
||||
const { code, data, show, msg } = response.data
|
||||
switch (code) {
|
||||
case RequestCodeEnum.SUCCESS:
|
||||
if (show) {
|
||||
msg && feedback.msgSuccess(msg)
|
||||
}
|
||||
return data
|
||||
case RequestCodeEnum.FAIL:
|
||||
if (show) {
|
||||
msg && feedback.msgError(msg)
|
||||
}
|
||||
return Promise.reject(data)
|
||||
case RequestCodeEnum.LOGIN_FAILURE:
|
||||
clearAuthInfo()
|
||||
router.push(PageEnum.LOGIN)
|
||||
return Promise.reject()
|
||||
case RequestCodeEnum.OPEN_NEW_PAGE:
|
||||
window.location.href = data.url
|
||||
return data
|
||||
case RequestCodeEnum.NOT_INSTALL:
|
||||
window.location.replace('/install/install.php')
|
||||
break
|
||||
default:
|
||||
return data
|
||||
}
|
||||
},
|
||||
responseInterceptorsCatchHook(error) {
|
||||
NProgress.done()
|
||||
if (error.code !== AxiosError.ERR_CANCELED) {
|
||||
error.message && feedback.msgError(error.message)
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
}
|
||||
|
||||
const defaultOptions: AxiosRequestConfig = {
|
||||
//接口超时时间
|
||||
timeout: configs.timeout,
|
||||
// 基础接口地址
|
||||
baseURL: configs.baseUrl,
|
||||
//请求头
|
||||
headers: { 'Content-Type': ContentTypeEnum.JSON, version: configs.version },
|
||||
// 处理 axios的钩子函数
|
||||
axiosHooks: axiosHooks,
|
||||
// 每个接口可以单独配置
|
||||
requestOptions: {
|
||||
// 是否将params视为data参数,仅限post请求
|
||||
isParamsToData: true,
|
||||
//是否返回默认的响应
|
||||
isReturnDefaultResponse: false,
|
||||
// 需要对返回数据进行处理
|
||||
isTransformResponse: true,
|
||||
// 接口拼接地址
|
||||
urlPrefix: configs.urlPrefix,
|
||||
// 忽略重复请求
|
||||
ignoreCancelToken: false,
|
||||
// 是否携带token
|
||||
withToken: true,
|
||||
// 开启请求超时重新发起请求请求机制
|
||||
isOpenRetry: true,
|
||||
// 重新请求次数
|
||||
retryCount: 2
|
||||
}
|
||||
}
|
||||
|
||||
function createAxios(opt?: Partial<AxiosRequestConfig>) {
|
||||
return new Axios(
|
||||
// 深度合并
|
||||
merge(defaultOptions, opt || {})
|
||||
)
|
||||
}
|
||||
const request = createAxios()
|
||||
export default request
|
||||
Vendored
+41
@@ -0,0 +1,41 @@
|
||||
import 'axios'
|
||||
|
||||
import type { AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
|
||||
|
||||
declare module 'axios' {
|
||||
// 扩展 RouteMeta
|
||||
interface AxiosRequestConfig {
|
||||
retryCount?: number
|
||||
axiosHooks?: AxiosHooks
|
||||
requestOptions: RequestOptions
|
||||
}
|
||||
}
|
||||
|
||||
export interface RequestOptions {
|
||||
isParamsToData: boolean
|
||||
isReturnDefaultResponse: boolean
|
||||
isTransformResponse: boolean
|
||||
urlPrefix: string
|
||||
ignoreCancelToken: boolean
|
||||
withToken: boolean
|
||||
isOpenRetry: boolean
|
||||
retryCount: number
|
||||
}
|
||||
|
||||
export interface AxiosHooks {
|
||||
requestInterceptorsHook?: (
|
||||
config: AxiosRequestConfig
|
||||
) => InternalAxiosRequestConfig | AxiosRequestConfig
|
||||
requestInterceptorsCatchHook?: (error: Error) => void
|
||||
responseInterceptorsHook?: (
|
||||
response: AxiosResponse<RequestData<T>>
|
||||
) => AxiosResponse<RequestData> | RequestData | T
|
||||
responseInterceptorsCatchHook?: (error: AxiosError) => void
|
||||
}
|
||||
|
||||
export interface RequestData<T = any> {
|
||||
code: number
|
||||
data: T
|
||||
msg: string
|
||||
show: boolean
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import colors from 'css-color-function'
|
||||
|
||||
const lightConfig = {
|
||||
'dark-2': 'shade(20%)',
|
||||
'light-3': 'tint(30%)',
|
||||
'light-5': 'tint(50%)',
|
||||
'light-7': 'tint(70%)',
|
||||
'light-8': 'tint(80%)',
|
||||
'light-9': 'tint(90%)'
|
||||
}
|
||||
|
||||
const darkConfig = {
|
||||
'light-3': 'shade(20%)',
|
||||
'light-5': 'shade(30%)',
|
||||
'light-7': 'shade(50%)',
|
||||
'light-8': 'shade(60%)',
|
||||
'light-9': 'shade(70%)',
|
||||
'dark-2': 'tint(20%)'
|
||||
}
|
||||
|
||||
const themeId = 'theme-vars'
|
||||
|
||||
/**
|
||||
* @author Jason
|
||||
* @description 用于生成elementui主题的行为变量
|
||||
* 可选值有primary、success、warning、danger、error、info
|
||||
*/
|
||||
|
||||
export const generateVars = (color: string, type = 'primary', isDark = false) => {
|
||||
const colos = {
|
||||
[`--el-color-${type}`]: color
|
||||
}
|
||||
const config: Record<string, string> = isDark ? darkConfig : lightConfig
|
||||
for (const key in config) {
|
||||
colos[`--el-color-${type}-${key}`] = `color(${color} ${config[key]})`
|
||||
}
|
||||
return colos
|
||||
}
|
||||
|
||||
/**
|
||||
* @author Jason
|
||||
* @description 用于设置css变量
|
||||
* @param key css变量key 如 --color-primary
|
||||
* @param value css变量值 如 #f40
|
||||
* @param dom dom元素
|
||||
*/
|
||||
export const setCssVar = (key: string, value: string, dom = document.documentElement) => {
|
||||
dom.style.setProperty(key, value)
|
||||
}
|
||||
|
||||
/**
|
||||
* @author Jason
|
||||
* @description 设置主题
|
||||
*/
|
||||
export const setTheme = (options: Record<string, string>, isDark = false) => {
|
||||
const varsMap: Record<string, string> = Object.keys(options).reduce((prev, key) => {
|
||||
return Object.assign(prev, generateVars(options[key], key, isDark))
|
||||
}, {})
|
||||
|
||||
let theme = Object.keys(varsMap).reduce((prev, key) => {
|
||||
const color = colors.convert(varsMap[key])
|
||||
return `${prev}${key}:${color};`
|
||||
}, '')
|
||||
theme = `:root{${theme}}`
|
||||
let style = document.getElementById(themeId)
|
||||
if (style) {
|
||||
style.innerHTML = theme
|
||||
return
|
||||
}
|
||||
style = document.createElement('style')
|
||||
style.setAttribute('type', 'text/css')
|
||||
style.setAttribute('id', themeId)
|
||||
style.innerHTML = theme
|
||||
document.head.append(style)
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
import { isObject } from '@vue/shared'
|
||||
import { cloneDeep } from 'lodash'
|
||||
|
||||
/**
|
||||
* @description 添加单位
|
||||
* @param {String | Number} value 值 100
|
||||
* @param {String} unit 单位 px em rem
|
||||
*/
|
||||
export const addUnit = (value: string | number, unit = 'px') => {
|
||||
return !Object.is(Number(value), NaN) ? `${value}${unit}` : value
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 添加单位
|
||||
* @param {unknown} value
|
||||
* @return {Boolean}
|
||||
*/
|
||||
export const isEmpty = (value: unknown) => {
|
||||
return value == null && typeof value == 'undefined'
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 树转数组,队列实现广度优先遍历
|
||||
* @param {Array} data 数据
|
||||
* @param {Object} props `{ children: 'children' }`
|
||||
*/
|
||||
|
||||
export const treeToArray = (data: any[], props = { children: 'children' }) => {
|
||||
data = cloneDeep(data)
|
||||
const { children } = props
|
||||
const newData = []
|
||||
const queue: any[] = []
|
||||
data.forEach((child: any) => queue.push(child))
|
||||
while (queue.length) {
|
||||
const item: any = queue.shift()
|
||||
if (item[children]) {
|
||||
item[children].forEach((child: any) => queue.push(child))
|
||||
delete item[children]
|
||||
}
|
||||
newData.push(item)
|
||||
}
|
||||
return newData
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 数组转
|
||||
* @param {Array} data 数据
|
||||
* @param {Object} props `{ parent: 'pid', children: 'children' }`
|
||||
*/
|
||||
|
||||
export const arrayToTree = (
|
||||
data: any[],
|
||||
props = { id: 'id', parentId: 'pid', children: 'children' }
|
||||
) => {
|
||||
data = cloneDeep(data)
|
||||
const { id, parentId, children } = props
|
||||
const result: any[] = []
|
||||
const map = new Map()
|
||||
data.forEach((item) => {
|
||||
map.set(item[id], item)
|
||||
const parent = map.get(item[parentId])
|
||||
if (parent) {
|
||||
parent[children] = parent[children] ?? []
|
||||
parent[children].push(item)
|
||||
} else {
|
||||
result.push(item)
|
||||
}
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 获取正确的路经
|
||||
* @param {String} path 数据
|
||||
*/
|
||||
export function getNormalPath(path: string) {
|
||||
if (path.length === 0 || !path || path == 'undefined') {
|
||||
return path
|
||||
}
|
||||
const newPath = path.replace('//', '/')
|
||||
const length = newPath.length
|
||||
if (newPath[length - 1] === '/') {
|
||||
return newPath.slice(0, length - 1)
|
||||
}
|
||||
return newPath
|
||||
}
|
||||
|
||||
/**
|
||||
* @description对象格式化为Query语法
|
||||
* @param { Object } params
|
||||
* @return {string} Query语法
|
||||
*/
|
||||
export function objectToQuery(params: Record<string, any>): string {
|
||||
let query = ''
|
||||
for (const props of Object.keys(params)) {
|
||||
const value = params[props]
|
||||
const part = encodeURIComponent(props) + '='
|
||||
if (!isEmpty(value)) {
|
||||
if (isObject(value)) {
|
||||
for (const key of Object.keys(value)) {
|
||||
if (!isEmpty(value[key])) {
|
||||
const params = props + '[' + key + ']'
|
||||
const subPart = encodeURIComponent(params) + '='
|
||||
query += subPart + encodeURIComponent(value[key]) + '&'
|
||||
}
|
||||
}
|
||||
} else {
|
||||
query += part + encodeURIComponent(value) + '&'
|
||||
}
|
||||
}
|
||||
}
|
||||
return query.slice(0, -1)
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 时间格式化
|
||||
* @param dateTime { number } 时间戳
|
||||
* @param fmt { string } 时间格式
|
||||
* @return { string }
|
||||
*/
|
||||
// yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合
|
||||
export const timeFormat = (dateTime: number, fmt = 'yyyy-mm-dd') => {
|
||||
// 如果为null,则格式化当前时间
|
||||
if (!dateTime) {
|
||||
dateTime = Number(new Date())
|
||||
}
|
||||
// 如果dateTime长度为10或者13,则为秒和毫秒的时间戳,如果超过13位,则为其他的时间格式
|
||||
if (dateTime.toString().length == 10) {
|
||||
dateTime *= 1000
|
||||
}
|
||||
const date = new Date(dateTime)
|
||||
let ret
|
||||
const opt: any = {
|
||||
'y+': date.getFullYear().toString(), // 年
|
||||
'm+': (date.getMonth() + 1).toString(), // 月
|
||||
'd+': date.getDate().toString(), // 日
|
||||
'h+': date.getHours().toString(), // 时
|
||||
'M+': date.getMinutes().toString(), // 分
|
||||
's+': date.getSeconds().toString() // 秒
|
||||
}
|
||||
for (const k in opt) {
|
||||
ret = new RegExp('(' + k + ')').exec(fmt)
|
||||
if (ret) {
|
||||
fmt = fmt.replace(
|
||||
ret[1],
|
||||
ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
|
||||
)
|
||||
}
|
||||
}
|
||||
return fmt
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 获取不重复的id
|
||||
* @param length { Number } id的长度
|
||||
* @return { String } id
|
||||
*/
|
||||
export const getNonDuplicateID = (length = 8) => {
|
||||
let idStr = Date.now().toString(36)
|
||||
idStr += Math.random().toString(36).substring(3, length)
|
||||
return idStr
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算颜色透明度减淡
|
||||
*/
|
||||
export const calcColor = (color: string, opacity: number): string => {
|
||||
// 规范化透明度值在 0 ~ 1 之间
|
||||
opacity = Math.min(1, Math.max(0, opacity))
|
||||
|
||||
// 检查颜色是否是 hex 格式
|
||||
const isHex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/
|
||||
const isRgb = /^rgb\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)$/
|
||||
const isRgba = /^rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*[0-9.]+\s*\)$/
|
||||
|
||||
let r: number = 0,
|
||||
g: number = 0,
|
||||
b: number = 0
|
||||
|
||||
if (isHex.test(color)) {
|
||||
// 如果是 hex 格式 (#ffffff 或 #fff)
|
||||
const hex = color.slice(1)
|
||||
|
||||
// 如果是3位短格式,扩展为6位
|
||||
const fullHex =
|
||||
hex.length === 3
|
||||
? hex
|
||||
.split('')
|
||||
.map((h) => h + h)
|
||||
.join('')
|
||||
: hex
|
||||
|
||||
// 转换为 RGB
|
||||
r = parseInt(fullHex.substring(0, 2), 16)
|
||||
g = parseInt(fullHex.substring(2, 4), 16)
|
||||
b = parseInt(fullHex.substring(4, 6), 16)
|
||||
} else if (isRgb.test(color)) {
|
||||
// 如果是 rgb 格式 (rgb(255, 255, 255))
|
||||
const rgbValues = color.match(/\d+/g)
|
||||
if (rgbValues) {
|
||||
r = parseInt(rgbValues[0])
|
||||
g = parseInt(rgbValues[1])
|
||||
b = parseInt(rgbValues[2])
|
||||
}
|
||||
} else if (isRgba.test(color)) {
|
||||
// 如果是 rgba 格式 (rgba(255, 255, 255, 1))
|
||||
const rgbaValues = color.match(/\d+(\.\d+)?/g)
|
||||
if (rgbaValues) {
|
||||
r = parseInt(rgbaValues[0])
|
||||
g = parseInt(rgbaValues[1])
|
||||
b = parseInt(rgbaValues[2])
|
||||
}
|
||||
} else {
|
||||
throw new Error('Unsupported color format')
|
||||
}
|
||||
|
||||
// 返回转换后的 rgba 颜色值
|
||||
return `rgba(${r}, ${g}, ${b}, ${opacity})`
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
/**
|
||||
* @param {string} path
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
export function isExternal(path: string) {
|
||||
return /^(https?:|mailto:|tel:)/.test(path)
|
||||
}
|
||||
Reference in New Issue
Block a user