初始化admin pc端

This commit is contained in:
Mrtangl
2022-04-08 10:42:44 +08:00
parent d9c9f27530
commit 19665b64fb
137 changed files with 11991 additions and 0 deletions

50
admin/src/utils/cache.ts Normal file
View File

@@ -0,0 +1,50 @@
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 false
}
},
get(key: string) {
key = this.getKey(key)
try {
const data = window.localStorage.getItem(key)
if (!data) {
return false
}
const { value, expire } = JSON.parse(data)
if (expire && expire < this.time()) {
window.localStorage.removeItem(key)
return false
}
return value
} catch (e) {
return false
}
},
//获取当前时间
time() {
return Math.round(new Date().getTime() / 1000)
},
remove(key: string) {
key = this.getKey(key)
window.localStorage.removeItem(key)
},
getKey(key: string) {
return this.key + key
}
}
export default cache

0
admin/src/utils/enum.ts Normal file
View File

View File

@@ -0,0 +1,86 @@
'use strict'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { version } from '@/config/app'
import store from '@/store'
import { throttle } from './util'
import router from '@/router'
import cache from './cache'
import { TOKEN } from '@/config/cachekey'
// 事件集
const eventResponse = {
// 成功
success: ({ show, msg, data }: any): Promise<any> => {
if (show * 1) {
ElMessage({ type: 'success', message: msg })
}
return data
},
// 失败
error: ({ show, msg }: any): Promise<any> => {
if (show * 1) {
ElMessage({ type: 'error', message: msg })
}
return Promise.reject(msg)
},
// 重定向
redirect: throttle(() => {
store.commit('user/setToken', '')
store.commit('user/setUser', {})
cache.remove(TOKEN)
router.push('/login')
return Promise.reject()
}),
// 打开新的页面
page: ({ data }: any): Promise<any> => {
window.location.href = data.url
return data
}
}
const request = axios.create({
baseURL: `${import.meta.env.VITE_APP_BASE_URL}/adminapi`,
timeout: 60 * 1000,
headers: {
'Content-Type': 'application/json',
version
}
})
request.interceptors.request.use(
config => {
const token = store.getters.token
// header参入Token
if (config.headers) {
config.headers.token = token
}
return config
},
error => {
return Promise.reject(error)
}
)
// Add a response interceptor
request.interceptors.response.use(
response => {
switch (response.data.code) {
case 1:
return eventResponse.success(response.data)
case 0:
return eventResponse.error(response.data)
case -1:
return eventResponse.redirect()
case 2:
return eventResponse.page(response.data)
}
},
error => {
console.log(error)
ElMessage({ type: 'error', message: error })
return Promise.reject(error)
}
)
export default request

5
admin/src/utils/type.ts Normal file
View File

@@ -0,0 +1,5 @@
// 页面模式
export enum PageMode {
'ADD' = 'add', // 添加
'EDIT' = 'edit' // 编辑
}

170
admin/src/utils/util.ts Normal file
View File

@@ -0,0 +1,170 @@
/**
* 工具方法
* 请谨慎操作,影响全局
*/
/**
* 深拷贝
* @param {any} target 需要深拷贝的对象
* @returns {Object}
*/
export function deepClone(target: any) {
if (typeof target !== 'object' || target === null) {
return target
}
const cloneResult: any = Array.isArray(target) ? [] : {}
for (const key in target) {
if (Object.prototype.hasOwnProperty.call(target, key)) {
const value = target[key]
if (typeof value === 'object' && value !== null) {
cloneResult[key] = deepClone(value)
} else {
cloneResult[key] = value
}
}
}
return cloneResult
}
/**
* 过滤对象属性
* @param { Object } target
* @param { Array } filters
* @return { Object } 过滤后的对象
*/
export function filterObject(target: any, filters: any[]) {
const _target = deepClone(target)
filters.map(key => delete _target[key])
return _target
}
/**
* 节流
* @param { Function } func
* @param { Number } time
* @param context
* @return { Function }
*/
export function throttle(func: () => any, time = 1000, context?: any): any {
let previous = new Date(0).getTime()
return function (...args: []) {
const now = new Date().getTime()
if (now - previous > time) {
previous = now
return func.apply(context, args)
}
}
}
/**
* Query语法格式化为对象
* @param { String } str
* @return { Object }
*/
export function queryToObject(str: string) {
const params: any = {}
for (const item of str.split('&')) {
params[item.split('=')[0]] = item.split('=')[1]
}
return params
}
/**
* 对象格式化为Query语法
* @param { Object } params
* @return {string} Query语法
*/
export function objectToQuery(params: any) {
let p = ''
if (typeof params === 'object') {
p = '?'
for (const props in params) {
p += `${props}=${params[props]}&`
}
p = p.slice(0, -1)
}
return p
}
/**
* @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).substr(3, length)
return idStr
}
/**
* @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
}
// /**
// *
// * @param {*} tree
// * @param {*} arr
// * @returns
// */
// export function flatten(tree = [], arr = []) {
// tree.forEach((item) => {
// const { children } = item
// arr.push(item)
// if (children) flatten(children, arr)
// })
// return arr
// }
/**
* @description 树状数组扁平化
* @param { Array } tree 树状结构数组
* @param { Array } arr 扁平化后的数组
* @param { String } childrenKey 子节点键名
* @return { Array } 扁平化后的数组
*/
export function flatten(tree = [], arr = [], childrenKey = 'children') {
tree.forEach(item => {
const children = item[childrenKey]
children ? flatten(children, arr, childrenKey) : arr.push(item)
})
return arr
}