init
This commit is contained in:
65
web/src/utils/arrayOperation.ts
Normal file
65
web/src/utils/arrayOperation.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* 判断两数组字符串是否相同(用于按钮权限验证),数组字符串中存在相同时会自动去重(按钮权限标识不会重复)
|
||||
* @param news 新数据
|
||||
* @param old 源数据
|
||||
* @returns 两数组相同返回 `true`,反之则反
|
||||
*/
|
||||
export function judementSameArr(newArr: unknown[] | string[], oldArr: string[]): boolean {
|
||||
const news = removeDuplicate(newArr);
|
||||
const olds = removeDuplicate(oldArr);
|
||||
let count = 0;
|
||||
const leng = news.length;
|
||||
for (let i in olds) {
|
||||
for (let j in news) {
|
||||
if (olds[i] === news[j]) count++;
|
||||
}
|
||||
}
|
||||
return count === leng ? true : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断两个对象是否相同
|
||||
* @param a 要比较的对象一
|
||||
* @param b 要比较的对象二
|
||||
* @returns 相同返回 true,反之则反
|
||||
*/
|
||||
export function isObjectValueEqual<T>(a: T, b: T): boolean {
|
||||
if (!a || !b) return false;
|
||||
let aProps = Object.getOwnPropertyNames(a);
|
||||
let bProps = Object.getOwnPropertyNames(b);
|
||||
if (aProps.length != bProps.length) return false;
|
||||
for (let i = 0; i < aProps.length; i++) {
|
||||
let propName = aProps[i];
|
||||
let propA = a[propName];
|
||||
let propB = b[propName];
|
||||
if (!b.hasOwnProperty(propName)) return false;
|
||||
if (propA instanceof Object) {
|
||||
if (!isObjectValueEqual(propA, propB)) return false;
|
||||
} else if (propA !== propB) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 数组、数组对象去重
|
||||
* @param arr 数组内容
|
||||
* @param attr 需要去重的键值(数组对象)
|
||||
* @returns
|
||||
*/
|
||||
export function removeDuplicate(arr: EmptyArrayType, attr?: string) {
|
||||
if (!Object.keys(arr).length) {
|
||||
return arr;
|
||||
} else {
|
||||
if (attr) {
|
||||
const obj: EmptyObjectType = {};
|
||||
return arr.reduce((cur: EmptyArrayType[], item: EmptyArrayType) => {
|
||||
obj[item[attr]] ? '' : (obj[item[attr]] = true && item[attr] && cur.push(item));
|
||||
return cur;
|
||||
}, []);
|
||||
} else {
|
||||
return [...new Set(arr)];
|
||||
}
|
||||
}
|
||||
}
|
||||
40
web/src/utils/authDirective.ts
Normal file
40
web/src/utils/authDirective.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import type { App } from 'vue';
|
||||
import { useUserInfo } from '/@/stores/userInfo';
|
||||
import { judementSameArr } from '/@/utils/arrayOperation';
|
||||
|
||||
/**
|
||||
* 用户权限指令
|
||||
* @directive 单个权限验证(v-auth="xxx")
|
||||
* @directive 多个权限验证,满足一个则显示(v-auths="[xxx,xxx]")
|
||||
* @directive 多个权限验证,全部满足则显示(v-auth-all="[xxx,xxx]")
|
||||
*/
|
||||
export function authDirective(app: App) {
|
||||
// 单个权限验证(v-auth="xxx")
|
||||
app.directive('auth', {
|
||||
mounted(el, binding) {
|
||||
const stores = useUserInfo();
|
||||
if (!stores.userInfos.authBtnList.some((v: string) => v === binding.value)) el.parentNode.removeChild(el);
|
||||
},
|
||||
});
|
||||
// 多个权限验证,满足一个则显示(v-auths="[xxx,xxx]")
|
||||
app.directive('auths', {
|
||||
mounted(el, binding) {
|
||||
let flag = false;
|
||||
const stores = useUserInfo();
|
||||
stores.userInfos.authBtnList.map((val: string) => {
|
||||
binding.value.map((v: string) => {
|
||||
if (val === v) flag = true;
|
||||
});
|
||||
});
|
||||
if (!flag) el.parentNode.removeChild(el);
|
||||
},
|
||||
});
|
||||
// 多个权限验证,全部满足则显示(v-auth-all="[xxx,xxx]")
|
||||
app.directive('auth-all', {
|
||||
mounted(el, binding) {
|
||||
const stores = useUserInfo();
|
||||
const flag = judementSameArr(binding.value, stores.userInfos.authBtnList);
|
||||
if (!flag) el.parentNode.removeChild(el);
|
||||
},
|
||||
});
|
||||
}
|
||||
38
web/src/utils/authFunction.ts
Normal file
38
web/src/utils/authFunction.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { useUserInfo } from '/@/stores/userInfo';
|
||||
import { judementSameArr } from '/@/utils/arrayOperation';
|
||||
|
||||
/**
|
||||
* 单个权限验证
|
||||
* @param value 权限值
|
||||
* @returns 有权限,返回 `true`,反之则反
|
||||
*/
|
||||
export function auth(value: string): boolean {
|
||||
const stores = useUserInfo();
|
||||
return stores.userInfos.authBtnList.some((v: string) => v === value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 多个权限验证,满足一个则为 true
|
||||
* @param value 权限值
|
||||
* @returns 有权限,返回 `true`,反之则反
|
||||
*/
|
||||
export function auths(value: Array<string>): boolean {
|
||||
let flag = false;
|
||||
const stores = useUserInfo();
|
||||
stores.userInfos.authBtnList.map((val: string) => {
|
||||
value.map((v: string) => {
|
||||
if (val === v) flag = true;
|
||||
});
|
||||
});
|
||||
return flag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 多个权限验证,全部满足则为 true
|
||||
* @param value 权限值
|
||||
* @returns 有权限,返回 `true`,反之则反
|
||||
*/
|
||||
export function authAll(value: Array<string>): boolean {
|
||||
const stores = useUserInfo();
|
||||
return judementSameArr(value, stores.userInfos.authBtnList);
|
||||
}
|
||||
67
web/src/utils/baseUrl.ts
Normal file
67
web/src/utils/baseUrl.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
import { pluginsAll } from '/@/views/plugins/index';
|
||||
|
||||
/**
|
||||
* @description 校验是否为租户模式。租户模式把域名替换成 域名 加端口
|
||||
*/
|
||||
export const getBaseURL = function () {
|
||||
var baseURL = import.meta.env.VITE_API_URL as any;
|
||||
var param = baseURL.split('/')[3] || '';
|
||||
// @ts-ignore
|
||||
if (pluginsAll && pluginsAll.indexOf('dvadmin3-tenants-web') !== -1 && (!param || baseURL.startsWith('/'))) {
|
||||
// 1.把127.0.0.1 替换成和前端一样域名
|
||||
// 2.把 ip 地址替换成和前端一样域名
|
||||
// 3.把 /api 或其他类似的替换成和前端一样域名
|
||||
// document.domain
|
||||
|
||||
var host = baseURL.split('/')[2];
|
||||
if (host) {
|
||||
var port = baseURL.split(':')[2] || 80;
|
||||
if (port === 80 || port === 443) {
|
||||
host = document.domain;
|
||||
} else {
|
||||
host = document.domain + ':' + port;
|
||||
}
|
||||
baseURL = baseURL.split('/')[0] + '//' + baseURL.split('/')[1] + host + '/' + param;
|
||||
} else {
|
||||
baseURL = location.protocol + '//' + location.hostname + (location.port ? ':' : '') + location.port + baseURL;
|
||||
}
|
||||
}
|
||||
if (!baseURL.endsWith('/')) {
|
||||
baseURL += '/';
|
||||
}
|
||||
return baseURL;
|
||||
};
|
||||
|
||||
export const getWsBaseURL = function () {
|
||||
let baseURL = import.meta.env.VITE_API_URL as any;
|
||||
let param = baseURL.split('/')[3] || '';
|
||||
// @ts-ignore
|
||||
if (pluginsAll && pluginsAll.indexOf('dvadmin3-tenants-web') !== -1 && (!param || baseURL.startsWith('/'))) {
|
||||
// 1.把127.0.0.1 替换成和前端一样域名
|
||||
// 2.把 ip 地址替换成和前端一样域名
|
||||
// 3.把 /api 或其他类似的替换成和前端一样域名
|
||||
// document.domain
|
||||
var host = baseURL.split('/')[2];
|
||||
if (host) {
|
||||
var port = baseURL.split(':')[2] || 80;
|
||||
if (port === 80 || port === 443) {
|
||||
host = document.domain;
|
||||
} else {
|
||||
host = document.domain + ':' + port;
|
||||
}
|
||||
baseURL = baseURL.split('/')[0] + '//' + baseURL.split('/')[1] + host + '/' + param;
|
||||
} else {
|
||||
baseURL = location.protocol + '//' + location.hostname + (location.port ? ':' : '') + location.port + baseURL;
|
||||
}
|
||||
} else if (param !== '' || baseURL.startsWith('/')) {
|
||||
baseURL = (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.hostname + (location.port ? ':' : '') + location.port + baseURL;
|
||||
}
|
||||
if (!baseURL.endsWith('/')) {
|
||||
baseURL += '/';
|
||||
}
|
||||
if (baseURL.startsWith('http')) {
|
||||
// https 也默认会被替换成 wss
|
||||
baseURL = baseURL.replace('http', 'ws');
|
||||
}
|
||||
return baseURL;
|
||||
};
|
||||
66
web/src/utils/commonFunction.ts
Normal file
66
web/src/utils/commonFunction.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
// 通用函数
|
||||
import useClipboard from 'vue-clipboard3';
|
||||
import { ElMessage } from 'element-plus';
|
||||
import { formatDate } from '/@/utils/formatTime';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
export default function () {
|
||||
const { t } = useI18n();
|
||||
const { toClipboard } = useClipboard();
|
||||
|
||||
// 百分比格式化
|
||||
const percentFormat = (row: EmptyArrayType, column: number, cellValue: string) => {
|
||||
return cellValue ? `${cellValue}%` : '-';
|
||||
};
|
||||
// 列表日期时间格式化
|
||||
const dateFormatYMD = (row: EmptyArrayType, column: number, cellValue: string) => {
|
||||
if (!cellValue) return '-';
|
||||
return formatDate(new Date(cellValue), 'YYYY-mm-dd');
|
||||
};
|
||||
// 列表日期时间格式化
|
||||
const dateFormatYMDHMS = (row: EmptyArrayType, column: number, cellValue: string) => {
|
||||
if (!cellValue) return '-';
|
||||
return formatDate(new Date(cellValue), 'YYYY-mm-dd HH:MM:SS');
|
||||
};
|
||||
// 列表日期时间格式化
|
||||
const dateFormatHMS = (row: EmptyArrayType, column: number, cellValue: string) => {
|
||||
if (!cellValue) return '-';
|
||||
let time = 0;
|
||||
if (typeof row === 'number') time = row;
|
||||
if (typeof cellValue === 'number') time = cellValue;
|
||||
return formatDate(new Date(time * 1000), 'HH:MM:SS');
|
||||
};
|
||||
// 小数格式化
|
||||
const scaleFormat = (value: string = '0', scale: number = 4) => {
|
||||
return Number.parseFloat(value).toFixed(scale);
|
||||
};
|
||||
// 小数格式化
|
||||
const scale2Format = (value: string = '0') => {
|
||||
return Number.parseFloat(value).toFixed(2);
|
||||
};
|
||||
// 点击复制文本
|
||||
const copyText = (text: string) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
//复制
|
||||
toClipboard(text);
|
||||
//下面可以设置复制成功的提示框等操作
|
||||
ElMessage.success(t('message.layout.copyTextSuccess'));
|
||||
resolve(text);
|
||||
} catch (e) {
|
||||
//复制失败
|
||||
ElMessage.error(t('message.layout.copyTextError'));
|
||||
reject(e);
|
||||
}
|
||||
});
|
||||
};
|
||||
return {
|
||||
percentFormat,
|
||||
dateFormatYMD,
|
||||
dateFormatYMDHMS,
|
||||
dateFormatHMS,
|
||||
scaleFormat,
|
||||
scale2Format,
|
||||
copyText,
|
||||
};
|
||||
}
|
||||
178
web/src/utils/customDirective.ts
Normal file
178
web/src/utils/customDirective.ts
Normal file
@@ -0,0 +1,178 @@
|
||||
import type { App } from 'vue';
|
||||
|
||||
/**
|
||||
* 按钮波浪指令
|
||||
* @directive 默认方式:v-waves,如 `<div v-waves></div>`
|
||||
* @directive 参数方式:v-waves=" |light|red|orange|purple|green|teal",如 `<div v-waves="'light'"></div>`
|
||||
*/
|
||||
export function wavesDirective(app: App) {
|
||||
app.directive('waves', {
|
||||
mounted(el, binding) {
|
||||
el.classList.add('waves-effect');
|
||||
binding.value && el.classList.add(`waves-${binding.value}`);
|
||||
function setConvertStyle(obj: { [key: string]: unknown }) {
|
||||
let style: string = '';
|
||||
for (let i in obj) {
|
||||
if (obj.hasOwnProperty(i)) style += `${i}:${obj[i]};`;
|
||||
}
|
||||
return style;
|
||||
}
|
||||
function onCurrentClick(e: { [key: string]: unknown }) {
|
||||
let elDiv = document.createElement('div');
|
||||
elDiv.classList.add('waves-ripple');
|
||||
el.appendChild(elDiv);
|
||||
let styles = {
|
||||
left: `${e.layerX}px`,
|
||||
top: `${e.layerY}px`,
|
||||
opacity: 1,
|
||||
transform: `scale(${(el.clientWidth / 100) * 10})`,
|
||||
'transition-duration': `750ms`,
|
||||
'transition-timing-function': `cubic-bezier(0.250, 0.460, 0.450, 0.940)`,
|
||||
};
|
||||
elDiv.setAttribute('style', setConvertStyle(styles));
|
||||
setTimeout(() => {
|
||||
elDiv.setAttribute(
|
||||
'style',
|
||||
setConvertStyle({
|
||||
opacity: 0,
|
||||
transform: styles.transform,
|
||||
left: styles.left,
|
||||
top: styles.top,
|
||||
})
|
||||
);
|
||||
setTimeout(() => {
|
||||
elDiv && el.removeChild(elDiv);
|
||||
}, 750);
|
||||
}, 450);
|
||||
}
|
||||
el.addEventListener('mousedown', onCurrentClick, false);
|
||||
},
|
||||
unmounted(el) {
|
||||
el.addEventListener('mousedown', () => {});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 自定义拖动指令
|
||||
* @description 使用方式:v-drag="[dragDom,dragHeader]",如 `<div v-drag="['.drag-container .el-dialog', '.drag-container .el-dialog__header']"></div>`
|
||||
* @description dragDom 要拖动的元素,dragHeader 要拖动的 Header 位置
|
||||
* @link 注意:https://github.com/element-plus/element-plus/issues/522
|
||||
* @lick 参考:https://blog.csdn.net/weixin_46391323/article/details/105228020?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-10&spm=1001.2101.3001.4242
|
||||
*/
|
||||
export function dragDirective(app: App) {
|
||||
app.directive('drag', {
|
||||
mounted(el, binding) {
|
||||
if (!binding.value) return false;
|
||||
|
||||
const dragDom = document.querySelector(binding.value[0]) as HTMLElement;
|
||||
const dragHeader = document.querySelector(binding.value[1]) as HTMLElement;
|
||||
|
||||
dragHeader.onmouseover = () => (dragHeader.style.cursor = `move`);
|
||||
|
||||
function down(e: any, type: string) {
|
||||
// 鼠标按下,计算当前元素距离可视区的距离
|
||||
const disX = type === 'pc' ? e.clientX - dragHeader.offsetLeft : e.touches[0].clientX - dragHeader.offsetLeft;
|
||||
const disY = type === 'pc' ? e.clientY - dragHeader.offsetTop : e.touches[0].clientY - dragHeader.offsetTop;
|
||||
|
||||
// body当前宽度
|
||||
const screenWidth = document.body.clientWidth;
|
||||
// 可见区域高度(应为body高度,可某些环境下无法获取)
|
||||
const screenHeight = document.documentElement.clientHeight;
|
||||
|
||||
// 对话框宽度
|
||||
const dragDomWidth = dragDom.offsetWidth;
|
||||
// 对话框高度
|
||||
const dragDomheight = dragDom.offsetHeight;
|
||||
|
||||
const minDragDomLeft = dragDom.offsetLeft;
|
||||
const maxDragDomLeft = screenWidth - dragDom.offsetLeft - dragDomWidth;
|
||||
|
||||
const minDragDomTop = dragDom.offsetTop;
|
||||
const maxDragDomTop = screenHeight - dragDom.offsetTop - dragDomheight;
|
||||
|
||||
// 获取到的值带px 正则匹配替换
|
||||
let styL: any = getComputedStyle(dragDom).left;
|
||||
let styT: any = getComputedStyle(dragDom).top;
|
||||
|
||||
// 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
|
||||
if (styL.includes('%')) {
|
||||
styL = +document.body.clientWidth * (+styL.replace(/\%/g, '') / 100);
|
||||
styT = +document.body.clientHeight * (+styT.replace(/\%/g, '') / 100);
|
||||
} else {
|
||||
styL = +styL.replace(/\px/g, '');
|
||||
styT = +styT.replace(/\px/g, '');
|
||||
}
|
||||
|
||||
return {
|
||||
disX,
|
||||
disY,
|
||||
minDragDomLeft,
|
||||
maxDragDomLeft,
|
||||
minDragDomTop,
|
||||
maxDragDomTop,
|
||||
styL,
|
||||
styT,
|
||||
};
|
||||
}
|
||||
|
||||
function move(e: any, type: string, obj: any) {
|
||||
let { disX, disY, minDragDomLeft, maxDragDomLeft, minDragDomTop, maxDragDomTop, styL, styT } = obj;
|
||||
|
||||
// 通过事件委托,计算移动的距离
|
||||
let left = type === 'pc' ? e.clientX - disX : e.touches[0].clientX - disX;
|
||||
let top = type === 'pc' ? e.clientY - disY : e.touches[0].clientY - disY;
|
||||
|
||||
// 边界处理
|
||||
if (-left > minDragDomLeft) {
|
||||
left = -minDragDomLeft;
|
||||
} else if (left > maxDragDomLeft) {
|
||||
left = maxDragDomLeft;
|
||||
}
|
||||
|
||||
if (-top > minDragDomTop) {
|
||||
top = -minDragDomTop;
|
||||
} else if (top > maxDragDomTop) {
|
||||
top = maxDragDomTop;
|
||||
}
|
||||
|
||||
// 移动当前元素
|
||||
dragDom.style.cssText += `;left:${left + styL}px;top:${top + styT}px;`;
|
||||
}
|
||||
|
||||
/**
|
||||
* pc端
|
||||
* onmousedown 鼠标按下触发事件
|
||||
* onmousemove 鼠标按下时持续触发事件
|
||||
* onmouseup 鼠标抬起触发事件
|
||||
*/
|
||||
dragHeader.onmousedown = (e) => {
|
||||
const obj = down(e, 'pc');
|
||||
document.onmousemove = (e) => {
|
||||
move(e, 'pc', obj);
|
||||
};
|
||||
document.onmouseup = () => {
|
||||
document.onmousemove = null;
|
||||
document.onmouseup = null;
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 移动端
|
||||
* ontouchstart 当按下手指时,触发ontouchstart
|
||||
* ontouchmove 当移动手指时,触发ontouchmove
|
||||
* ontouchend 当移走手指时,触发ontouchend
|
||||
*/
|
||||
dragHeader.ontouchstart = (e) => {
|
||||
const obj = down(e, 'app');
|
||||
document.ontouchmove = (e) => {
|
||||
move(e, 'app', obj);
|
||||
};
|
||||
document.ontouchend = () => {
|
||||
document.ontouchmove = null;
|
||||
document.ontouchend = null;
|
||||
};
|
||||
};
|
||||
},
|
||||
});
|
||||
}
|
||||
11
web/src/utils/dictionary.ts
Normal file
11
web/src/utils/dictionary.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { toRaw } from 'vue';
|
||||
import { DictionaryStore } from '/@/stores/dictionary';
|
||||
|
||||
/**
|
||||
* @method 获取指定name字典
|
||||
*/
|
||||
export const dictionary = (name: string) => {
|
||||
const dict = DictionaryStore()
|
||||
const dictionary = toRaw(dict.data)
|
||||
return dictionary[name]
|
||||
}
|
||||
18
web/src/utils/directive.ts
Normal file
18
web/src/utils/directive.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import type { App } from 'vue';
|
||||
import { authDirective } from '/@/utils/authDirective';
|
||||
import { wavesDirective, dragDirective } from '/@/utils/customDirective';
|
||||
|
||||
/**
|
||||
* 导出指令方法:v-xxx
|
||||
* @methods authDirective 用户权限指令,用法:v-auth
|
||||
* @methods wavesDirective 按钮波浪指令,用法:v-waves
|
||||
* @methods dragDirective 自定义拖动指令,用法:v-drag
|
||||
*/
|
||||
export function directive(app: App) {
|
||||
// 用户权限指令
|
||||
authDirective(app);
|
||||
// 按钮波浪指令
|
||||
wavesDirective(app);
|
||||
// 自定义拖动指令
|
||||
dragDirective(app);
|
||||
}
|
||||
137
web/src/utils/formatTime.ts
Normal file
137
web/src/utils/formatTime.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* 时间日期转换
|
||||
* @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 {
|
||||
let we = date.getDay(); // 星期
|
||||
let z = getWeek(date); // 周
|
||||
let qut = Math.floor((date.getMonth() + 3) / 3).toString(); // 季度
|
||||
const opt: { [key: string]: string } = {
|
||||
'Y+': date.getFullYear().toString(), // 年
|
||||
'm+': (date.getMonth() + 1).toString(), // 月(月份从0开始,要+1)
|
||||
'd+': date.getDate().toString(), // 日
|
||||
'H+': date.getHours().toString(), // 时
|
||||
'M+': date.getMinutes().toString(), // 分
|
||||
'S+': date.getSeconds().toString(), // 秒
|
||||
'q+': qut, // 季度
|
||||
};
|
||||
// 中文数字 (星期)
|
||||
const week: { [key: string]: string } = {
|
||||
'0': '日',
|
||||
'1': '一',
|
||||
'2': '二',
|
||||
'3': '三',
|
||||
'4': '四',
|
||||
'5': '五',
|
||||
'6': '六',
|
||||
};
|
||||
// 中文数字(季度)
|
||||
const quarter: { [key: string]: string } = {
|
||||
'1': '一',
|
||||
'2': '二',
|
||||
'3': '三',
|
||||
'4': '四',
|
||||
};
|
||||
if (/(W+)/.test(format))
|
||||
format = format.replace(RegExp.$1, RegExp.$1.length > 1 ? (RegExp.$1.length > 2 ? '星期' + week[we] : '周' + week[we]) : week[we]);
|
||||
if (/(Q+)/.test(format)) format = format.replace(RegExp.$1, RegExp.$1.length == 4 ? '第' + quarter[qut] + '季度' : quarter[qut]);
|
||||
if (/(Z+)/.test(format)) format = format.replace(RegExp.$1, RegExp.$1.length == 3 ? '第' + z + '周' : z + '');
|
||||
for (let k in opt) {
|
||||
let r = new RegExp('(' + k + ')').exec(format);
|
||||
// 若输入的长度不为1,则前面补零
|
||||
if (r) format = format.replace(r[1], RegExp.$1.length == 1 ? opt[k] : opt[k].padStart(RegExp.$1.length, '0'));
|
||||
}
|
||||
return format;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前日期是第几周
|
||||
* @param dateTime 当前传入的日期值
|
||||
* @returns 返回第几周数字值
|
||||
*/
|
||||
export function getWeek(dateTime: Date): number {
|
||||
let temptTime = new Date(dateTime.getTime());
|
||||
// 周几
|
||||
let weekday = temptTime.getDay() || 7;
|
||||
// 周1+5天=周六
|
||||
temptTime.setDate(temptTime.getDate() - weekday + 1 + 5);
|
||||
let firstDay = new Date(temptTime.getFullYear(), 0, 1);
|
||||
let dayOfWeek = firstDay.getDay();
|
||||
let spendDay = 1;
|
||||
if (dayOfWeek != 0) spendDay = 7 - dayOfWeek + 1;
|
||||
firstDay = new Date(temptTime.getFullYear(), 0, 1 + spendDay);
|
||||
let d = Math.ceil((temptTime.valueOf() - firstDay.valueOf()) / 86400000);
|
||||
let result = Math.ceil(d / 7);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将时间转换为 `几秒前`、`几分钟前`、`几小时前`、`几天前`
|
||||
* @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: string = 'YYYY-mm-dd'): 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天
|
||||
let 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 {
|
||||
let 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 '夜里好';
|
||||
}
|
||||
101
web/src/utils/getStyleSheets.ts
Normal file
101
web/src/utils/getStyleSheets.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
import { nextTick } from 'vue';
|
||||
import * as svg from '@element-plus/icons-vue';
|
||||
|
||||
// 获取阿里字体图标
|
||||
const getAlicdnIconfont = () => {
|
||||
return new Promise((resolve, reject) => {
|
||||
nextTick(() => {
|
||||
const styles: any = document.styleSheets;
|
||||
let sheetsList = [];
|
||||
let sheetsIconList = [];
|
||||
for (let i = 0; i < styles.length; i++) {
|
||||
if (styles[i].href && styles[i].href.indexOf('at.alicdn.com') > -1) {
|
||||
sheetsList.push(styles[i]);
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < sheetsList.length; i++) {
|
||||
for (let j = 0; j < sheetsList[i].cssRules.length; j++) {
|
||||
if (sheetsList[i].cssRules[j].selectorText && sheetsList[i].cssRules[j].selectorText.indexOf('.icon-') > -1) {
|
||||
sheetsIconList.push(
|
||||
`${sheetsList[i].cssRules[j].selectorText.substring(1, sheetsList[i].cssRules[j].selectorText.length).replace(/\:\:before/gi, '')}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (sheetsIconList.length > 0) resolve(sheetsIconList);
|
||||
else reject('未获取到值,请刷新重试');
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// 初始化获取 css 样式,获取 element plus 自带 svg 图标,增加了 ele- 前缀,使用时:ele-Aim
|
||||
const getElementPlusIconfont = () => {
|
||||
return new Promise((resolve, reject) => {
|
||||
nextTick(() => {
|
||||
const icons = svg as any;
|
||||
const sheetsIconList = [];
|
||||
for (const i in icons) {
|
||||
sheetsIconList.push(`ele-${icons[i].name}`);
|
||||
}
|
||||
if (sheetsIconList.length > 0) resolve(sheetsIconList);
|
||||
else reject('未获取到值,请刷新重试');
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// 初始化获取 css 样式,这里使用 fontawesome 的图标
|
||||
const getAwesomeIconfont = () => {
|
||||
return new Promise((resolve, reject) => {
|
||||
nextTick(() => {
|
||||
const styles: any = document.styleSheets;
|
||||
let sheetsList = [];
|
||||
let sheetsIconList = [];
|
||||
for (let i = 0; i < styles.length; i++) {
|
||||
if (styles[i].href && styles[i].href.indexOf('netdna.bootstrapcdn.com') > -1) {
|
||||
sheetsList.push(styles[i]);
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < sheetsList.length; i++) {
|
||||
for (let j = 0; j < sheetsList[i].cssRules.length; j++) {
|
||||
if (
|
||||
sheetsList[i].cssRules[j].selectorText &&
|
||||
sheetsList[i].cssRules[j].selectorText.indexOf('.fa-') === 0 &&
|
||||
sheetsList[i].cssRules[j].selectorText.indexOf(',') === -1
|
||||
) {
|
||||
if (/::before/.test(sheetsList[i].cssRules[j].selectorText)) {
|
||||
sheetsIconList.push(
|
||||
`${sheetsList[i].cssRules[j].selectorText.substring(1, sheetsList[i].cssRules[j].selectorText.length).replace(/\:\:before/gi, '')}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (sheetsIconList.length > 0) resolve(sheetsIconList.reverse());
|
||||
else reject('未获取到值,请刷新重试');
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取字体图标 `document.styleSheets`
|
||||
* @method ali 获取阿里字体图标 `<i class="iconfont 图标类名"></i>`
|
||||
* @method ele 获取 element plus 自带图标 `<i class="图标类名"></i>`
|
||||
* @method ali 获取 fontawesome 的图标 `<i class="fa 图标类名"></i>`
|
||||
*/
|
||||
const initIconfont = {
|
||||
// iconfont
|
||||
ali: () => {
|
||||
return getAlicdnIconfont();
|
||||
},
|
||||
// element plus
|
||||
ele: () => {
|
||||
return getElementPlusIconfont();
|
||||
},
|
||||
// fontawesome
|
||||
awe: () => {
|
||||
return getAwesomeIconfont();
|
||||
},
|
||||
};
|
||||
|
||||
// 导出方法
|
||||
export default initIconfont;
|
||||
44
web/src/utils/loading.ts
Normal file
44
web/src/utils/loading.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { nextTick } from 'vue';
|
||||
import '/@/theme/loading.scss';
|
||||
|
||||
/**
|
||||
* 页面全局 Loading
|
||||
* @method start 创建 loading
|
||||
* @method done 移除 loading
|
||||
*/
|
||||
export const NextLoading = {
|
||||
// 创建 loading
|
||||
start: () => {
|
||||
const bodys: Element = document.body;
|
||||
const div = <HTMLElement>document.createElement('div');
|
||||
div.setAttribute('class', 'loading-next');
|
||||
const htmls = `
|
||||
<div class="loading-next-box">
|
||||
<div class="loading-next-box-warp">
|
||||
<div class="loading-next-box-item"></div>
|
||||
<div class="loading-next-box-item"></div>
|
||||
<div class="loading-next-box-item"></div>
|
||||
<div class="loading-next-box-item"></div>
|
||||
<div class="loading-next-box-item"></div>
|
||||
<div class="loading-next-box-item"></div>
|
||||
<div class="loading-next-box-item"></div>
|
||||
<div class="loading-next-box-item"></div>
|
||||
<div class="loading-next-box-item"></div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
div.innerHTML = htmls;
|
||||
bodys.insertBefore(div, bodys.childNodes[0]);
|
||||
window.nextLoading = true;
|
||||
},
|
||||
// 移除 loading
|
||||
done: (time: number = 0) => {
|
||||
nextTick(() => {
|
||||
setTimeout(() => {
|
||||
window.nextLoading = false;
|
||||
const el = <HTMLElement>document.querySelector('.loading-next');
|
||||
el?.parentNode?.removeChild(el);
|
||||
}, time);
|
||||
});
|
||||
},
|
||||
};
|
||||
49
web/src/utils/menu.ts
Normal file
49
web/src/utils/menu.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import XEUtils from "xe-utils"
|
||||
|
||||
/**
|
||||
* @description: 处理后端菜单数据格式
|
||||
* @param {Array} menuData
|
||||
* @return {*}
|
||||
*/
|
||||
export const handleMenu = (menuData: Array<any>) => {
|
||||
// 先处理menu meta数据转换
|
||||
const handleMeta = (item: any) => {
|
||||
item.meta = {
|
||||
title: item.title,
|
||||
isLink: item.is_link,
|
||||
isHide: !item.visible,
|
||||
isKeepAlive: item.cache,
|
||||
isAffix: false,
|
||||
isIframe: false,
|
||||
roles: ['admin'],
|
||||
icon: item.icon
|
||||
}
|
||||
item.name = item.component_name
|
||||
return item
|
||||
}
|
||||
menuData.forEach((val) => {
|
||||
handleMeta(val)
|
||||
val.path = val.web_path
|
||||
})
|
||||
|
||||
const data = XEUtils.toArrayTree(menuData, {
|
||||
parentKey: 'parent',
|
||||
strict: true,
|
||||
})
|
||||
const menu = [
|
||||
{
|
||||
path: '/home', name: 'home', component: '/system/home/index', meta: {
|
||||
title: 'message.router.home',
|
||||
isLink: '',
|
||||
isHide: false,
|
||||
isKeepAlive: true,
|
||||
isAffix: true,
|
||||
isIframe: false,
|
||||
roles: ['admin'],
|
||||
icon: 'iconfont icon-shouye'
|
||||
}
|
||||
},
|
||||
...data
|
||||
]
|
||||
return menu
|
||||
}
|
||||
33
web/src/utils/message.ts
Normal file
33
web/src/utils/message.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { ElMessage, ElNotification, MessageOptions } from 'element-plus';
|
||||
|
||||
export function message(message: string, option?: MessageOptions) {
|
||||
ElMessage({ message, ...option });
|
||||
}
|
||||
export function successMessage(message: string, option?: MessageOptions) {
|
||||
ElMessage({ message, type: 'success' });
|
||||
}
|
||||
export function warningMessage(message: string, option?: MessageOptions) {
|
||||
ElMessage({ message, ...option, type: 'warning' });
|
||||
}
|
||||
export function errorMessage(message: string, option?: MessageOptions) {
|
||||
ElMessage({ message, ...option, type: 'error' });
|
||||
}
|
||||
export function infoMessage(message: string, option?: MessageOptions) {
|
||||
ElMessage({ message, ...option, type: 'info' });
|
||||
}
|
||||
|
||||
export function notification(message: string) {
|
||||
ElNotification({ message });
|
||||
}
|
||||
export function successNotification(message: string) {
|
||||
ElNotification({ message, type: 'success' });
|
||||
}
|
||||
export function warningNotification(message: string) {
|
||||
ElNotification({ message, type: 'warning' });
|
||||
}
|
||||
export function errorNotification(message: string) {
|
||||
ElNotification({ message, type: 'error' });
|
||||
}
|
||||
export function infoNotification(message: string) {
|
||||
ElNotification({ message, type: 'info' });
|
||||
}
|
||||
8
web/src/utils/mitt.ts
Normal file
8
web/src/utils/mitt.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
// https://www.npmjs.com/package/mitt
|
||||
import mitt, { Emitter } from 'mitt';
|
||||
|
||||
// 类型
|
||||
const emitter: Emitter<MittType> = mitt<MittType>();
|
||||
|
||||
// 导出
|
||||
export default emitter;
|
||||
218
web/src/utils/other.ts
Normal file
218
web/src/utils/other.ts
Normal file
@@ -0,0 +1,218 @@
|
||||
import { nextTick, defineAsyncComponent } from 'vue';
|
||||
import type { App } from 'vue';
|
||||
import * as svg from '@element-plus/icons-vue';
|
||||
import router from '/@/router/index';
|
||||
import pinia from '/@/stores/index';
|
||||
import { storeToRefs } from 'pinia';
|
||||
import { useThemeConfig } from '/@/stores/themeConfig';
|
||||
import { i18n } from '/@/i18n/index';
|
||||
import { Local } from '/@/utils/storage';
|
||||
import { verifyUrl } from '/@/utils/toolsValidate';
|
||||
|
||||
// 引入组件
|
||||
const SvgIcon = defineAsyncComponent(() => import('/@/components/svgIcon/index.vue'));
|
||||
|
||||
/**
|
||||
* 导出全局注册 element plus svg 图标
|
||||
* @param app vue 实例
|
||||
* @description 使用:https://element-plus.gitee.io/zh-CN/component/icon.html
|
||||
*/
|
||||
export function elSvg(app: App) {
|
||||
const icons = svg as any;
|
||||
for (const i in icons) {
|
||||
app.component(`ele-${icons[i].name}`, icons[i]);
|
||||
}
|
||||
app.component('SvgIcon', SvgIcon);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置浏览器标题国际化
|
||||
* @method const title = useTitle(); ==> title()
|
||||
*/
|
||||
export function useTitle() {
|
||||
const stores = useThemeConfig(pinia);
|
||||
const { themeConfig } = storeToRefs(stores);
|
||||
nextTick(() => {
|
||||
let webTitle = '';
|
||||
let globalTitle: string = themeConfig.value.globalTitle;
|
||||
const { path, meta } = router.currentRoute.value;
|
||||
if (path === '/login') {
|
||||
webTitle = <string>meta.title;
|
||||
} else {
|
||||
webTitle = setTagsViewNameI18n(router.currentRoute.value);
|
||||
}
|
||||
document.title = `${webTitle} - ${globalTitle}` || globalTitle;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置 自定义 tagsView 名称、 自定义 tagsView 名称国际化
|
||||
* @param params 路由 query、params 中的 tagsViewName
|
||||
* @returns 返回当前 tagsViewName 名称
|
||||
*/
|
||||
export function setTagsViewNameI18n(item: any) {
|
||||
let tagsViewName: string = '';
|
||||
const { query, params, meta } = item;
|
||||
if (query?.tagsViewName || params?.tagsViewName) {
|
||||
if (/\/zh-cn|en|zh-tw\//.test(query?.tagsViewName) || /\/zh-cn|en|zh-tw\//.test(params?.tagsViewName)) {
|
||||
// 国际化
|
||||
const urlTagsParams = (query?.tagsViewName && JSON.parse(query?.tagsViewName)) || (params?.tagsViewName && JSON.parse(params?.tagsViewName));
|
||||
tagsViewName = urlTagsParams[i18n.global.locale.value];
|
||||
} else {
|
||||
// 非国际化
|
||||
tagsViewName = query?.tagsViewName || params?.tagsViewName;
|
||||
}
|
||||
} else {
|
||||
// 非自定义 tagsView 名称
|
||||
tagsViewName = i18n.global.t(meta.title);
|
||||
}
|
||||
return tagsViewName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 图片懒加载
|
||||
* @param el dom 目标元素
|
||||
* @param arr 列表数据
|
||||
* @description data-xxx 属性用于存储页面或应用程序的私有自定义数据
|
||||
*/
|
||||
export const lazyImg = (el: string, arr: EmptyArrayType) => {
|
||||
const io = new IntersectionObserver((res) => {
|
||||
res.forEach((v: any) => {
|
||||
if (v.isIntersecting) {
|
||||
const { img, key } = v.target.dataset;
|
||||
v.target.src = img;
|
||||
v.target.onload = () => {
|
||||
io.unobserve(v.target);
|
||||
arr[key]['loading'] = false;
|
||||
};
|
||||
}
|
||||
});
|
||||
});
|
||||
nextTick(() => {
|
||||
document.querySelectorAll(el).forEach((img) => io.observe(img));
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 全局组件大小
|
||||
* @returns 返回 `window.localStorage` 中读取的缓存值 `globalComponentSize`
|
||||
*/
|
||||
export const globalComponentSize = (): string => {
|
||||
const stores = useThemeConfig(pinia);
|
||||
const { themeConfig } = storeToRefs(stores);
|
||||
return Local.get('themeConfig')?.globalComponentSize || themeConfig.value?.globalComponentSize;
|
||||
};
|
||||
|
||||
/**
|
||||
* 对象深克隆
|
||||
* @param obj 源对象
|
||||
* @returns 克隆后的对象
|
||||
*/
|
||||
export function deepClone(obj: EmptyObjectType) {
|
||||
let newObj: EmptyObjectType;
|
||||
try {
|
||||
newObj = obj.push ? [] : {};
|
||||
} catch (error) {
|
||||
newObj = {};
|
||||
}
|
||||
for (let attr in obj) {
|
||||
if (obj[attr] && typeof obj[attr] === 'object') {
|
||||
newObj[attr] = deepClone(obj[attr]);
|
||||
} else {
|
||||
newObj[attr] = obj[attr];
|
||||
}
|
||||
}
|
||||
return newObj;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否是移动端
|
||||
*/
|
||||
export function isMobile() {
|
||||
if (
|
||||
navigator.userAgent.match(
|
||||
/('phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone')/i
|
||||
)
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断数组对象中所有属性是否为空,为空则删除当前行对象
|
||||
* @description @感谢大黄
|
||||
* @param list 数组对象
|
||||
* @returns 删除空值后的数组对象
|
||||
*/
|
||||
export function handleEmpty(list: EmptyArrayType) {
|
||||
const arr = [];
|
||||
for (const i in list) {
|
||||
const d = [];
|
||||
for (const j in list[i]) {
|
||||
d.push(list[i][j]);
|
||||
}
|
||||
const leng = d.filter((item) => item === '').length;
|
||||
if (leng !== d.length) {
|
||||
arr.push(list[i]);
|
||||
}
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开外部链接
|
||||
* @param val 当前点击项菜单
|
||||
*/
|
||||
export function handleOpenLink(val: RouteItem) {
|
||||
const { origin, pathname } = window.location;
|
||||
router.push(val.path);
|
||||
if (verifyUrl(<string>val.meta?.isLink)) window.open(val.meta?.isLink);
|
||||
else window.open(`${origin}${pathname}#${val.meta?.isLink}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一批量导出
|
||||
* @method elSvg 导出全局注册 element plus svg 图标
|
||||
* @method useTitle 设置浏览器标题国际化
|
||||
* @method setTagsViewNameI18n 设置 自定义 tagsView 名称、 自定义 tagsView 名称国际化
|
||||
* @method lazyImg 图片懒加载
|
||||
* @method globalComponentSize() element plus 全局组件大小
|
||||
* @method deepClone 对象深克隆
|
||||
* @method isMobile 判断是否是移动端
|
||||
* @method handleEmpty 判断数组对象中所有属性是否为空,为空则删除当前行对象
|
||||
* @method handleOpenLink 打开外部链接
|
||||
*/
|
||||
const other = {
|
||||
elSvg: (app: App) => {
|
||||
elSvg(app);
|
||||
},
|
||||
useTitle: () => {
|
||||
useTitle();
|
||||
},
|
||||
setTagsViewNameI18n(route: RouteToFrom) {
|
||||
return setTagsViewNameI18n(route);
|
||||
},
|
||||
lazyImg: (el: string, arr: EmptyArrayType) => {
|
||||
lazyImg(el, arr);
|
||||
},
|
||||
globalComponentSize: () => {
|
||||
return globalComponentSize();
|
||||
},
|
||||
deepClone: (obj: EmptyObjectType) => {
|
||||
return deepClone(obj);
|
||||
},
|
||||
isMobile: () => {
|
||||
return isMobile();
|
||||
},
|
||||
handleEmpty: (list: EmptyArrayType) => {
|
||||
return handleEmpty(list);
|
||||
},
|
||||
handleOpenLink: (val: RouteItem) => {
|
||||
handleOpenLink(val);
|
||||
},
|
||||
};
|
||||
|
||||
// 统一批量导出
|
||||
export default other;
|
||||
67
web/src/utils/request.ts
Normal file
67
web/src/utils/request.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
import { Session } from '/@/utils/storage';
|
||||
import qs from 'qs';
|
||||
|
||||
// 配置新建一个 axios 实例
|
||||
const service: AxiosInstance = axios.create({
|
||||
baseURL: import.meta.env.VITE_API_URL,
|
||||
timeout: 50000,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
paramsSerializer: {
|
||||
serialize(params) {
|
||||
return qs.stringify(params, { allowDots: true });
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// 添加请求拦截器
|
||||
service.interceptors.request.use(
|
||||
(config: AxiosRequestConfig) => {
|
||||
// 在发送请求之前做些什么 token
|
||||
if (Session.get('token')) {
|
||||
config.headers!['Authorization'] = `${Session.get('token')}`;
|
||||
}
|
||||
return config;
|
||||
},
|
||||
(error) => {
|
||||
// 对请求错误做些什么
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
// 添加响应拦截器
|
||||
service.interceptors.response.use(
|
||||
(response) => {
|
||||
// 对响应数据做点什么
|
||||
const res = response.data;
|
||||
if (res.code && res.code !== 0) {
|
||||
// `token` 过期或者账号已在别处登录
|
||||
if (res.code === 401 || res.code === 4001) {
|
||||
Session.clear(); // 清除浏览器全部临时缓存
|
||||
window.location.href = '/'; // 去登录页
|
||||
ElMessageBox.alert('你已被登出,请重新登录', '提示', {})
|
||||
.then(() => {})
|
||||
.catch(() => {});
|
||||
}
|
||||
return Promise.reject(service.interceptors.response);
|
||||
} else {
|
||||
return response.data;
|
||||
}
|
||||
},
|
||||
(error) => {
|
||||
// 对响应错误做点什么
|
||||
if (error.message.indexOf('timeout') != -1) {
|
||||
ElMessage.error('网络超时');
|
||||
} else if (error.message == 'Network Error') {
|
||||
ElMessage.error('网络连接错误');
|
||||
} else {
|
||||
if (error.response.data) ElMessage.error(error.response.statusText);
|
||||
else ElMessage.error('接口路径找不到');
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
// 导出 axios 实例
|
||||
export default service;
|
||||
227
web/src/utils/service.ts
Normal file
227
web/src/utils/service.ts
Normal file
@@ -0,0 +1,227 @@
|
||||
import axios from 'axios';
|
||||
import { get } from 'lodash-es';
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
import type { Action } from 'element-plus';
|
||||
|
||||
// @ts-ignore
|
||||
import { errorLog, errorCreate } from './tools.ts';
|
||||
// import { env } from "/src/utils/util.env";
|
||||
// import { useUserStore } from "../store/modules/user";
|
||||
import { Local, Session } from '/@/utils/storage';
|
||||
import qs from 'qs';
|
||||
import { getBaseURL } from './baseUrl';
|
||||
/**
|
||||
* @description 创建请求实例
|
||||
*/
|
||||
function createService() {
|
||||
// 创建一个 axios 实例
|
||||
const service = axios.create({
|
||||
timeout: 20000,
|
||||
headers: {
|
||||
'Content-Type': 'application/json;charset=utf-8',
|
||||
},
|
||||
paramsSerializer: {
|
||||
serialize(params) {
|
||||
interface paramsObj {
|
||||
[key: string]: any;
|
||||
}
|
||||
let result:paramsObj = {};
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
if (value !== '') {
|
||||
result[key] = value;
|
||||
}
|
||||
if(typeof value === 'boolean'){
|
||||
result[key] = value? 'True': 'False';
|
||||
}
|
||||
}
|
||||
return qs.stringify(result);
|
||||
},
|
||||
},
|
||||
});
|
||||
// 请求拦截
|
||||
service.interceptors.request.use(
|
||||
(config) => config,
|
||||
(error) => {
|
||||
// 发送失败
|
||||
console.log(error);
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
// 响应拦截
|
||||
service.interceptors.response.use(
|
||||
(response) => {
|
||||
if (response.config.responseType === 'blob') {
|
||||
return response;
|
||||
}
|
||||
// dataAxios 是 axios 返回数据中的 data
|
||||
const dataAxios = response.data;
|
||||
// 这个状态码是和后端约定的
|
||||
const { code } = dataAxios;
|
||||
// swagger判断
|
||||
if (dataAxios.swagger != undefined) {
|
||||
return dataAxios;
|
||||
}
|
||||
// 根据 code 进行判断
|
||||
if (code === undefined) {
|
||||
// 如果没有 code 代表这不是项目后端开发的接口
|
||||
errorCreate(`非标准返回:${dataAxios}, ${response.config.url}`, false);
|
||||
return dataAxios;
|
||||
} else {
|
||||
// 有 code 代表这是一个后端接口 可以进行进一步的判断
|
||||
switch (code) {
|
||||
case 400:
|
||||
// Local.clear();
|
||||
// Session.clear();
|
||||
errorCreate(`${dataAxios.msg}: ${response.config.url}`);
|
||||
// window.location.reload();
|
||||
break;
|
||||
case 401:
|
||||
Local.clear();
|
||||
Session.clear();
|
||||
dataAxios.msg = '登录认证失败,请重新登录';
|
||||
ElMessageBox.alert(dataAxios.msg, '提示', {
|
||||
confirmButtonText: 'OK',
|
||||
callback: (action: Action) => {
|
||||
window.location.reload();
|
||||
},
|
||||
});
|
||||
errorCreate(`${dataAxios.msg}: ${response.config.url}`);
|
||||
break;
|
||||
case 2000:
|
||||
// @ts-ignore
|
||||
if (response.config.unpack === false) {
|
||||
//如果不需要解包
|
||||
return dataAxios;
|
||||
}
|
||||
return dataAxios;
|
||||
case 4000:
|
||||
errorCreate(`${dataAxios.msg}: ${response.config.url}`);
|
||||
return Promise.reject(dataAxios.msg);
|
||||
default:
|
||||
// 不是正确的 code
|
||||
errorCreate(`${dataAxios.msg}: ${response.config.url}`);
|
||||
return dataAxios;
|
||||
}
|
||||
}
|
||||
},
|
||||
(error) => {
|
||||
const status = get(error, 'response.status');
|
||||
switch (status) {
|
||||
case 400:
|
||||
error.message = '请求错误';
|
||||
break;
|
||||
case 401:
|
||||
Local.clear();
|
||||
Session.clear();
|
||||
error.message = '登录授权过期,请重新登录';
|
||||
ElMessageBox.alert(error.message, '提示', {
|
||||
confirmButtonText: 'OK',
|
||||
callback: (action: Action) => {
|
||||
window.location.reload();
|
||||
},
|
||||
});
|
||||
break;
|
||||
case 403:
|
||||
error.message = '拒绝访问';
|
||||
break;
|
||||
case 404:
|
||||
error.message = `请求地址出错: ${error.response.config.url}`;
|
||||
break;
|
||||
case 408:
|
||||
error.message = '请求超时';
|
||||
break;
|
||||
case 500:
|
||||
error.message = '服务器内部错误';
|
||||
break;
|
||||
case 501:
|
||||
error.message = '服务未实现';
|
||||
break;
|
||||
case 502:
|
||||
error.message = '网关错误';
|
||||
break;
|
||||
case 503:
|
||||
error.message = '服务不可用';
|
||||
break;
|
||||
case 504:
|
||||
error.message = '网关超时';
|
||||
break;
|
||||
case 505:
|
||||
error.message = 'HTTP版本不受支持';
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
errorLog(error);
|
||||
if (status === 401) {
|
||||
// const userStore = useUserStore();
|
||||
// userStore.logout();
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
return service;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 创建请求方法
|
||||
* @param {Object} service axios 实例
|
||||
*/
|
||||
function createRequestFunction(service: any) {
|
||||
return function (config: any) {
|
||||
const configDefault = {
|
||||
headers: {
|
||||
'Content-Type': get(config, 'headers.Content-Type', 'application/json'),
|
||||
},
|
||||
timeout: 5000,
|
||||
baseURL: getBaseURL(),
|
||||
data: {},
|
||||
};
|
||||
|
||||
// const token = userStore.getToken;
|
||||
const token = Session.get('token');
|
||||
if (token != null) {
|
||||
// @ts-ignore
|
||||
configDefault.headers.Authorization = 'JWT ' + token;
|
||||
}
|
||||
return service(Object.assign(configDefault, config));
|
||||
};
|
||||
}
|
||||
|
||||
// 用于真实网络请求的实例和请求方法
|
||||
export const service = createService();
|
||||
export const request = createRequestFunction(service);
|
||||
|
||||
// 用于模拟网络请求的实例和请求方法
|
||||
export const serviceForMock = createService();
|
||||
export const requestForMock = createRequestFunction(serviceForMock);
|
||||
|
||||
/**
|
||||
* 下载文件
|
||||
* @param url
|
||||
* @param params
|
||||
* @param method
|
||||
* @param filename
|
||||
*/
|
||||
export const downloadFile = function ({url,params,method,filename = '文件导出'}:any) {
|
||||
request({
|
||||
url: url,
|
||||
method: method,
|
||||
params: params,
|
||||
responseType: 'blob'
|
||||
// headers: {Accept: 'application/vnd.openxmlformats-officedocument'}
|
||||
}).then((res:any) => {
|
||||
const xlsxName = window.decodeURI(res.headers['content-disposition'].split('=')[1])
|
||||
const fileName = xlsxName || `${filename}.xlsx`
|
||||
if (res) {
|
||||
const blob = new Blob([res.data], { type: 'charset=utf-8' })
|
||||
const elink = document.createElement('a')
|
||||
elink.download = fileName
|
||||
elink.style.display = 'none'
|
||||
elink.href = URL.createObjectURL(blob)
|
||||
document.body.appendChild(elink)
|
||||
elink.click()
|
||||
URL.revokeObjectURL(elink.href) // 释放URL 对象0
|
||||
document.body.removeChild(elink)
|
||||
}
|
||||
})
|
||||
}
|
||||
49
web/src/utils/setIconfont.ts
Normal file
49
web/src/utils/setIconfont.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
// 字体图标 url
|
||||
const cssCdnUrlList: Array<string> = [
|
||||
'//at.alicdn.com/t/font_2298093_y6u00apwst.css',
|
||||
'//at.alicdn.com/t/c/font_3882322_9ah7y8m9175.css', //dvadmin3项目用icon
|
||||
'//netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css',
|
||||
];
|
||||
// 第三方 js url
|
||||
const jsCdnUrlList: Array<string> = [];
|
||||
|
||||
// 动态批量设置字体图标
|
||||
export function setCssCdn() {
|
||||
if (cssCdnUrlList.length <= 0) return false;
|
||||
cssCdnUrlList.map((v) => {
|
||||
let link = document.createElement('link');
|
||||
link.rel = 'stylesheet';
|
||||
link.href = v;
|
||||
link.crossOrigin = 'anonymous';
|
||||
document.getElementsByTagName('head')[0].appendChild(link);
|
||||
});
|
||||
}
|
||||
|
||||
// 动态批量设置第三方js
|
||||
export function setJsCdn() {
|
||||
if (jsCdnUrlList.length <= 0) return false;
|
||||
jsCdnUrlList.map((v) => {
|
||||
let link = document.createElement('script');
|
||||
link.src = v;
|
||||
document.body.appendChild(link);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量设置字体图标、动态js
|
||||
* @method cssCdn 动态批量设置字体图标
|
||||
* @method jsCdn 动态批量设置第三方js
|
||||
*/
|
||||
const setIntroduction = {
|
||||
// 设置css
|
||||
cssCdn: () => {
|
||||
setCssCdn();
|
||||
},
|
||||
// 设置js
|
||||
jsCdn: () => {
|
||||
setJsCdn();
|
||||
},
|
||||
};
|
||||
|
||||
// 导出函数方法
|
||||
export default setIntroduction;
|
||||
59
web/src/utils/storage.ts
Normal file
59
web/src/utils/storage.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import Cookies from 'js-cookie';
|
||||
|
||||
/**
|
||||
* window.localStorage 浏览器永久缓存
|
||||
* @method set 设置永久缓存
|
||||
* @method get 获取永久缓存
|
||||
* @method remove 移除永久缓存
|
||||
* @method clear 移除全部永久缓存
|
||||
*/
|
||||
export const Local = {
|
||||
// 设置永久缓存
|
||||
set(key: string, val: any) {
|
||||
window.localStorage.setItem(key, JSON.stringify(val));
|
||||
},
|
||||
// 获取永久缓存
|
||||
get(key: string) {
|
||||
let json = <string>window.localStorage.getItem(key);
|
||||
return JSON.parse(json);
|
||||
},
|
||||
// 移除永久缓存
|
||||
remove(key: string) {
|
||||
window.localStorage.removeItem(key);
|
||||
},
|
||||
// 移除全部永久缓存
|
||||
clear() {
|
||||
window.localStorage.clear();
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* window.sessionStorage 浏览器临时缓存
|
||||
* @method set 设置临时缓存
|
||||
* @method get 获取临时缓存
|
||||
* @method remove 移除临时缓存
|
||||
* @method clear 移除全部临时缓存
|
||||
*/
|
||||
export const Session = {
|
||||
// 设置临时缓存
|
||||
set(key: string, val: any) {
|
||||
if (key === 'token') return Cookies.set(key, val);
|
||||
window.sessionStorage.setItem(key, JSON.stringify(val));
|
||||
},
|
||||
// 获取临时缓存
|
||||
get(key: string) {
|
||||
if (key === 'token') return Cookies.get(key);
|
||||
let json = <string>window.sessionStorage.getItem(key);
|
||||
return JSON.parse(json);
|
||||
},
|
||||
// 移除临时缓存
|
||||
remove(key: string) {
|
||||
if (key === 'token') return Cookies.remove(key);
|
||||
window.sessionStorage.removeItem(key);
|
||||
},
|
||||
// 移除全部临时缓存
|
||||
clear() {
|
||||
Cookies.remove('token');
|
||||
window.sessionStorage.clear();
|
||||
},
|
||||
};
|
||||
63
web/src/utils/theme.ts
Normal file
63
web/src/utils/theme.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { ElMessage } from 'element-plus';
|
||||
|
||||
/**
|
||||
* 颜色转换函数
|
||||
* @method hexToRgb hex 颜色转 rgb 颜色
|
||||
* @method rgbToHex rgb 颜色转 Hex 颜色
|
||||
* @method getDarkColor 加深颜色值
|
||||
* @method getLightColor 变浅颜色值
|
||||
*/
|
||||
export function useChangeColor() {
|
||||
// str 颜色值字符串
|
||||
const hexToRgb = (str: string): any => {
|
||||
let hexs: any = '';
|
||||
let reg = /^\#?[0-9A-Fa-f]{6}$/;
|
||||
if (!reg.test(str)) {
|
||||
ElMessage.warning('输入错误的hex');
|
||||
return '';
|
||||
}
|
||||
str = str.replace('#', '');
|
||||
hexs = str.match(/../g);
|
||||
for (let i = 0; i < 3; i++) hexs[i] = parseInt(hexs[i], 16);
|
||||
return hexs;
|
||||
};
|
||||
// r 代表红色 | g 代表绿色 | b 代表蓝色
|
||||
const rgbToHex = (r: any, g: any, b: any): string => {
|
||||
let reg = /^\d{1,3}$/;
|
||||
if (!reg.test(r) || !reg.test(g) || !reg.test(b)) {
|
||||
ElMessage.warning('输入错误的rgb颜色值');
|
||||
return '';
|
||||
}
|
||||
let hexs = [r.toString(16), g.toString(16), b.toString(16)];
|
||||
for (let i = 0; i < 3; i++) if (hexs[i].length == 1) hexs[i] = `0${hexs[i]}`;
|
||||
return `#${hexs.join('')}`;
|
||||
};
|
||||
// color 颜色值字符串 | level 变浅的程度,限0-1之间
|
||||
const getDarkColor = (color: string, level: number): string => {
|
||||
let reg = /^\#?[0-9A-Fa-f]{6}$/;
|
||||
if (!reg.test(color)) {
|
||||
ElMessage.warning('输入错误的hex颜色值');
|
||||
return '';
|
||||
}
|
||||
let rgb = useChangeColor().hexToRgb(color);
|
||||
for (let i = 0; i < 3; i++) rgb[i] = Math.floor(rgb[i] * (1 - level));
|
||||
return useChangeColor().rgbToHex(rgb[0], rgb[1], rgb[2]);
|
||||
};
|
||||
// color 颜色值字符串 | level 加深的程度,限0-1之间
|
||||
const getLightColor = (color: string, level: number): string => {
|
||||
let reg = /^\#?[0-9A-Fa-f]{6}$/;
|
||||
if (!reg.test(color)) {
|
||||
ElMessage.warning('输入错误的hex颜色值');
|
||||
return '';
|
||||
}
|
||||
let rgb = useChangeColor().hexToRgb(color);
|
||||
for (let i = 0; i < 3; i++) rgb[i] = Math.floor((255 - rgb[i]) * level + rgb[i]);
|
||||
return useChangeColor().rgbToHex(rgb[0], rgb[1], rgb[2]);
|
||||
};
|
||||
return {
|
||||
hexToRgb,
|
||||
rgbToHex,
|
||||
getDarkColor,
|
||||
getLightColor,
|
||||
};
|
||||
}
|
||||
101
web/src/utils/tools.ts
Normal file
101
web/src/utils/tools.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* @description 安全地解析 json 字符串
|
||||
* @param {String} jsonString 需要解析的 json 字符串
|
||||
* @param {String} defaultValue 默认值
|
||||
*/
|
||||
import { uiContext } from '@fast-crud/fast-crud';
|
||||
|
||||
export function parse(jsonString = '{}', defaultValue = {}) {
|
||||
let result = defaultValue;
|
||||
try {
|
||||
result = JSON.parse(jsonString);
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 接口请求返回
|
||||
* @param {Any} data 返回值
|
||||
* @param {String} msg 状态信息
|
||||
* @param {Number} code 状态码
|
||||
*/
|
||||
export function response(data = {}, msg = '', code = 0) {
|
||||
return [200, { code, msg, data }];
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 接口请求返回 正确返回
|
||||
* @param {Any} data 返回值
|
||||
* @param {String} msg 状态信息
|
||||
*/
|
||||
export function responseSuccess(data = {}, msg = '成功') {
|
||||
return response(data, msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 接口请求返回 错误返回
|
||||
* @param {Any} data 返回值
|
||||
* @param {String} msg 状态信息
|
||||
* @param {Number} code 状态码
|
||||
*/
|
||||
export function responseError(data = {}, msg = '请求失败', code = 500) {
|
||||
return response(data, msg, code);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 记录和显示错误
|
||||
* @param {Error} error 错误对象
|
||||
*/
|
||||
export function errorLog(error: any, notification = true) {
|
||||
// 打印到控制台
|
||||
console.error(error);
|
||||
// 显示提示
|
||||
if (notification) {
|
||||
uiContext.get().notification.error({ message: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 创建一个错误
|
||||
* @param {String} msg 错误信息
|
||||
*/
|
||||
export function errorCreate(msg: any, notification = true) {
|
||||
const error = new Error(msg);
|
||||
errorLog(error, notification);
|
||||
// throw error;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description base64转file
|
||||
* @param {String} base64 base64字符串
|
||||
* @param {String} fileName 文件名
|
||||
*/
|
||||
export function base64ToFile(base64: any, fileName: string) {
|
||||
// 将base64按照 , 进行分割 将前缀 与后续内容分隔开
|
||||
let data = base64.split(',');
|
||||
// 利用正则表达式 从前缀中获取图片的类型信息(image/png、image/jpeg、image/webp等)
|
||||
let type = data[0].match(/:(.*?);/)[1];
|
||||
// 从图片的类型信息中 获取具体的文件格式后缀(png、jpeg、webp)
|
||||
let 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文件对象
|
||||
// new File(bits, name, options)
|
||||
const file = new File([u8arr], `${fileName}.${suffix}`, {
|
||||
type: type,
|
||||
});
|
||||
// 将File文件对象返回给方法的调用者
|
||||
return file;
|
||||
}
|
||||
370
web/src/utils/toolsValidate.ts
Normal file
370
web/src/utils/toolsValidate.ts
Normal file
@@ -0,0 +1,370 @@
|
||||
/**
|
||||
* 2020.11.29 lyt 整理
|
||||
* 工具类集合,适用于平时开发
|
||||
* 新增多行注释信息,鼠标放到方法名即可查看
|
||||
*/
|
||||
|
||||
/**
|
||||
* 验证百分比(不可以小数)
|
||||
* @param val 当前值字符串
|
||||
* @returns 返回处理后的字符串
|
||||
*/
|
||||
export function verifyNumberPercentage(val: string): string {
|
||||
// 匹配空格
|
||||
let v = val.replace(/(^\s*)|(\s*$)/g, '');
|
||||
// 只能是数字和小数点,不能是其他输入
|
||||
v = v.replace(/[^\d]/g, '');
|
||||
// 不能以0开始
|
||||
v = v.replace(/^0/g, '');
|
||||
// 数字超过100,赋值成最大值100
|
||||
v = v.replace(/^[1-9]\d\d{1,3}$/, '100');
|
||||
// 返回结果
|
||||
return v;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证百分比(可以小数)
|
||||
* @param val 当前值字符串
|
||||
* @returns 返回处理后的字符串
|
||||
*/
|
||||
export function verifyNumberPercentageFloat(val: string): string {
|
||||
let v = verifyNumberIntegerAndFloat(val);
|
||||
// 数字超过100,赋值成最大值100
|
||||
v = v.replace(/^[1-9]\d\d{1,3}$/, '100');
|
||||
// 超过100之后不给再输入值
|
||||
v = v.replace(/^100\.$/, '100');
|
||||
// 返回结果
|
||||
return v;
|
||||
}
|
||||
|
||||
/**
|
||||
* 小数或整数(不可以负数)
|
||||
* @param val 当前值字符串
|
||||
* @returns 返回处理后的字符串
|
||||
*/
|
||||
export function verifyNumberIntegerAndFloat(val: string) {
|
||||
// 匹配空格
|
||||
let v = val.replace(/(^\s*)|(\s*$)/g, '');
|
||||
// 只能是数字和小数点,不能是其他输入
|
||||
v = v.replace(/[^\d.]/g, '');
|
||||
// 以0开始只能输入一个
|
||||
v = v.replace(/^0{2}$/g, '0');
|
||||
// 保证第一位只能是数字,不能是点
|
||||
v = v.replace(/^\./g, '');
|
||||
// 小数只能出现1位
|
||||
v = v.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
|
||||
// 小数点后面保留2位
|
||||
v = v.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
|
||||
// 返回结果
|
||||
return v;
|
||||
}
|
||||
|
||||
/**
|
||||
* 正整数验证
|
||||
* @param val 当前值字符串
|
||||
* @returns 返回处理后的字符串
|
||||
*/
|
||||
export function verifiyNumberInteger(val: string) {
|
||||
// 匹配空格
|
||||
let v = val.replace(/(^\s*)|(\s*$)/g, '');
|
||||
// 去掉 '.' , 防止贴贴的时候出现问题 如 0.1.12.12
|
||||
v = v.replace(/[\.]*/g, '');
|
||||
// 去掉以 0 开始后面的数, 防止贴贴的时候出现问题 如 00121323
|
||||
v = v.replace(/(^0[\d]*)$/g, '0');
|
||||
// 首位是0,只能出现一次
|
||||
v = v.replace(/^0\d$/g, '0');
|
||||
// 只匹配数字
|
||||
v = v.replace(/[^\d]/g, '');
|
||||
// 返回结果
|
||||
return v;
|
||||
}
|
||||
|
||||
/**
|
||||
* 去掉中文及空格
|
||||
* @param val 当前值字符串
|
||||
* @returns 返回处理后的字符串
|
||||
*/
|
||||
export function verifyCnAndSpace(val: string) {
|
||||
// 匹配中文与空格
|
||||
let v = val.replace(/[\u4e00-\u9fa5\s]+/g, '');
|
||||
// 匹配空格
|
||||
v = v.replace(/(^\s*)|(\s*$)/g, '');
|
||||
// 返回结果
|
||||
return v;
|
||||
}
|
||||
|
||||
/**
|
||||
* 去掉英文及空格
|
||||
* @param val 当前值字符串
|
||||
* @returns 返回处理后的字符串
|
||||
*/
|
||||
export function verifyEnAndSpace(val: string) {
|
||||
// 匹配英文与空格
|
||||
let v = val.replace(/[a-zA-Z]+/g, '');
|
||||
// 匹配空格
|
||||
v = v.replace(/(^\s*)|(\s*$)/g, '');
|
||||
// 返回结果
|
||||
return v;
|
||||
}
|
||||
|
||||
/**
|
||||
* 禁止输入空格
|
||||
* @param val 当前值字符串
|
||||
* @returns 返回处理后的字符串
|
||||
*/
|
||||
export function verifyAndSpace(val: string) {
|
||||
// 匹配空格
|
||||
let v = val.replace(/(^\s*)|(\s*$)/g, '');
|
||||
// 返回结果
|
||||
return v;
|
||||
}
|
||||
|
||||
/**
|
||||
* 金额用 `,` 区分开
|
||||
* @param val 当前值字符串
|
||||
* @returns 返回处理后的字符串
|
||||
*/
|
||||
export function verifyNumberComma(val: string) {
|
||||
// 调用小数或整数(不可以负数)方法
|
||||
let v: any = verifyNumberIntegerAndFloat(val);
|
||||
// 字符串转成数组
|
||||
v = v.toString().split('.');
|
||||
// \B 匹配非单词边界,两边都是单词字符或者两边都是非单词字符
|
||||
v[0] = v[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
||||
// 数组转字符串
|
||||
v = v.join('.');
|
||||
// 返回结果
|
||||
return v;
|
||||
}
|
||||
|
||||
/**
|
||||
* 匹配文字变色(搜索时)
|
||||
* @param val 当前值字符串
|
||||
* @param text 要处理的字符串值
|
||||
* @param color 搜索到时字体高亮颜色
|
||||
* @returns 返回处理后的字符串
|
||||
*/
|
||||
export function verifyTextColor(val: string, text = '', color = 'red') {
|
||||
// 返回内容,添加颜色
|
||||
let v = text.replace(new RegExp(val, 'gi'), `<span style='color: ${color}'>${val}</span>`);
|
||||
// 返回结果
|
||||
return v;
|
||||
}
|
||||
|
||||
/**
|
||||
* 数字转中文大写
|
||||
* @param val 当前值字符串
|
||||
* @param unit 默认:仟佰拾亿仟佰拾万仟佰拾元角分
|
||||
* @returns 返回处理后的字符串
|
||||
*/
|
||||
export function verifyNumberCnUppercase(val: any, unit = '仟佰拾亿仟佰拾万仟佰拾元角分', v = '') {
|
||||
// 当前内容字符串添加 2个0,为什么??
|
||||
val += '00';
|
||||
// 返回某个指定的字符串值在字符串中首次出现的位置,没有出现,则该方法返回 -1
|
||||
let lookup = val.indexOf('.');
|
||||
// substring:不包含结束下标内容,substr:包含结束下标内容
|
||||
if (lookup >= 0) val = val.substring(0, lookup) + val.substr(lookup + 1, 2);
|
||||
// 根据内容 val 的长度,截取返回对应大写
|
||||
unit = unit.substr(unit.length - val.length);
|
||||
// 循环截取拼接大写
|
||||
for (let i = 0; i < val.length; i++) {
|
||||
v += '零壹贰叁肆伍陆柒捌玖'.substr(val.substr(i, 1), 1) + unit.substr(i, 1);
|
||||
}
|
||||
// 正则处理
|
||||
v = v
|
||||
.replace(/零角零分$/, '整')
|
||||
.replace(/零[仟佰拾]/g, '零')
|
||||
.replace(/零{2,}/g, '零')
|
||||
.replace(/零([亿|万])/g, '$1')
|
||||
.replace(/零+元/, '元')
|
||||
.replace(/亿零{0,3}万/, '亿')
|
||||
.replace(/^元/, '零元');
|
||||
// 返回结果
|
||||
return v;
|
||||
}
|
||||
|
||||
/**
|
||||
* 手机号码
|
||||
* @param val 当前值字符串
|
||||
* @returns 返回 true: 手机号码正确
|
||||
*/
|
||||
export function verifyPhone(val: string) {
|
||||
// false: 手机号码不正确
|
||||
if (!/^((\+|00)86)?1((3[\d])|(4[5,6,7,9])|(5[0-3,5-9])|(6[5-7])|(7[0-8])|(8[\d])|(9[1,8,9]))\d{8}$/.test(val)) return false;
|
||||
// true: 手机号码正确
|
||||
else return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 国内电话号码
|
||||
* @param val 当前值字符串
|
||||
* @returns 返回 true: 国内电话号码正确
|
||||
*/
|
||||
export function verifyTelPhone(val: string) {
|
||||
// false: 国内电话号码不正确
|
||||
if (!/\d{3}-\d{8}|\d{4}-\d{7}/.test(val)) return false;
|
||||
// true: 国内电话号码正确
|
||||
else return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录账号 (字母开头,允许5-16字节,允许字母数字下划线)
|
||||
* @param val 当前值字符串
|
||||
* @returns 返回 true: 登录账号正确
|
||||
*/
|
||||
export function verifyAccount(val: string) {
|
||||
// false: 登录账号不正确
|
||||
if (!/^[a-zA-Z][a-zA-Z0-9_]{4,15}$/.test(val)) return false;
|
||||
// true: 登录账号正确
|
||||
else return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 密码 (以字母开头,长度在6~16之间,只能包含字母、数字和下划线)
|
||||
* @param val 当前值字符串
|
||||
* @returns 返回 true: 密码正确
|
||||
*/
|
||||
export function verifyPassword(val: string) {
|
||||
// false: 密码不正确
|
||||
if (!/^[a-zA-Z]\w{5,15}$/.test(val)) return false;
|
||||
// true: 密码正确
|
||||
else return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 强密码 (字母+数字+特殊字符,长度在6-16之间)
|
||||
* @param val 当前值字符串
|
||||
* @returns 返回 true: 强密码正确
|
||||
*/
|
||||
export function verifyPasswordPowerful(val: string) {
|
||||
// false: 强密码不正确
|
||||
if (!/^(?![a-zA-z]+$)(?!\d+$)(?![!@#$%^&\.*]+$)(?![a-zA-z\d]+$)(?![a-zA-z!@#$%^&\.*]+$)(?![\d!@#$%^&\.*]+$)[a-zA-Z\d!@#$%^&\.*]{6,16}$/.test(val))
|
||||
return false;
|
||||
// true: 强密码正确
|
||||
else return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 密码强度
|
||||
* @param val 当前值字符串
|
||||
* @description 弱:纯数字,纯字母,纯特殊字符
|
||||
* @description 中:字母+数字,字母+特殊字符,数字+特殊字符
|
||||
* @description 强:字母+数字+特殊字符
|
||||
* @returns 返回处理后的字符串:弱、中、强
|
||||
*/
|
||||
export function verifyPasswordStrength(val: string) {
|
||||
let v = '';
|
||||
// 弱:纯数字,纯字母,纯特殊字符
|
||||
if (/^(?:\d+|[a-zA-Z]+|[!@#$%^&\.*]+){6,16}$/.test(val)) v = '弱';
|
||||
// 中:字母+数字,字母+特殊字符,数字+特殊字符
|
||||
if (/^(?![a-zA-z]+$)(?!\d+$)(?![!@#$%^&\.*]+$)[a-zA-Z\d!@#$%^&\.*]{6,16}$/.test(val)) v = '中';
|
||||
// 强:字母+数字+特殊字符
|
||||
if (/^(?![a-zA-z]+$)(?!\d+$)(?![!@#$%^&\.*]+$)(?![a-zA-z\d]+$)(?![a-zA-z!@#$%^&\.*]+$)(?![\d!@#$%^&\.*]+$)[a-zA-Z\d!@#$%^&\.*]{6,16}$/.test(val))
|
||||
v = '强';
|
||||
// 返回结果
|
||||
return v;
|
||||
}
|
||||
|
||||
/**
|
||||
* IP地址
|
||||
* @param val 当前值字符串
|
||||
* @returns 返回 true: IP地址正确
|
||||
*/
|
||||
export function verifyIPAddress(val: string) {
|
||||
// false: IP地址不正确
|
||||
if (
|
||||
!/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/.test(
|
||||
val
|
||||
)
|
||||
)
|
||||
return false;
|
||||
// true: IP地址正确
|
||||
else return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 邮箱
|
||||
* @param val 当前值字符串
|
||||
* @returns 返回 true: 邮箱正确
|
||||
*/
|
||||
export function verifyEmail(val: string) {
|
||||
// false: 邮箱不正确
|
||||
if (
|
||||
!/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
|
||||
val
|
||||
)
|
||||
)
|
||||
return false;
|
||||
// true: 邮箱正确
|
||||
else return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 身份证
|
||||
* @param val 当前值字符串
|
||||
* @returns 返回 true: 身份证正确
|
||||
*/
|
||||
export function verifyIdCard(val: string) {
|
||||
// false: 身份证不正确
|
||||
if (!/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(val)) return false;
|
||||
// true: 身份证正确
|
||||
else return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 姓名
|
||||
* @param val 当前值字符串
|
||||
* @returns 返回 true: 姓名正确
|
||||
*/
|
||||
export function verifyFullName(val: string) {
|
||||
// false: 姓名不正确
|
||||
if (!/^[\u4e00-\u9fa5]{1,6}(·[\u4e00-\u9fa5]{1,6}){0,2}$/.test(val)) return false;
|
||||
// true: 姓名正确
|
||||
else return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 邮政编码
|
||||
* @param val 当前值字符串
|
||||
* @returns 返回 true: 邮政编码正确
|
||||
*/
|
||||
export function verifyPostalCode(val: string) {
|
||||
// false: 邮政编码不正确
|
||||
if (!/^[1-9][0-9]{5}$/.test(val)) return false;
|
||||
// true: 邮政编码正确
|
||||
else return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* url 处理
|
||||
* @param val 当前值字符串
|
||||
* @returns 返回 true: url 正确
|
||||
*/
|
||||
export function verifyUrl(val: string) {
|
||||
// false: url不正确
|
||||
if (
|
||||
!/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(
|
||||
val
|
||||
)
|
||||
)
|
||||
return false;
|
||||
// true: url正确
|
||||
else return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 车牌号
|
||||
* @param val 当前值字符串
|
||||
* @returns 返回 true:车牌号正确
|
||||
*/
|
||||
export function verifyCarNum(val: string) {
|
||||
// false: 车牌号不正确
|
||||
if (
|
||||
!/^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/.test(
|
||||
val
|
||||
)
|
||||
)
|
||||
return false;
|
||||
// true:车牌号正确
|
||||
else return true;
|
||||
}
|
||||
47
web/src/utils/wartermark.ts
Normal file
47
web/src/utils/wartermark.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
// 页面添加水印效果
|
||||
const setWatermark = (str: string) => {
|
||||
const id = '1.23452384164.123412416';
|
||||
if (document.getElementById(id) !== null) document.body.removeChild(<HTMLElement>document.getElementById(id));
|
||||
const can = document.createElement('canvas');
|
||||
can.width = 200;
|
||||
can.height = 130;
|
||||
const cans = <CanvasRenderingContext2D>can.getContext('2d');
|
||||
cans.rotate((-20 * Math.PI) / 180);
|
||||
cans.font = '12px Vedana';
|
||||
cans.fillStyle = 'rgba(200, 200, 200, 0.30)';
|
||||
cans.textBaseline = 'middle';
|
||||
cans.fillText(str, can.width / 10, can.height / 2);
|
||||
const div = document.createElement('div');
|
||||
div.id = id;
|
||||
div.style.pointerEvents = 'none';
|
||||
div.style.top = '0px';
|
||||
div.style.left = '0px';
|
||||
div.style.position = 'fixed';
|
||||
div.style.zIndex = '10000000';
|
||||
div.style.width = `${document.documentElement.clientWidth}px`;
|
||||
div.style.height = `${document.documentElement.clientHeight}px`;
|
||||
div.style.background = `url(${can.toDataURL('image/png')}) left top repeat`;
|
||||
document.body.appendChild(div);
|
||||
return id;
|
||||
};
|
||||
|
||||
/**
|
||||
* 页面添加水印效果
|
||||
* @method set 设置水印
|
||||
* @method del 删除水印
|
||||
*/
|
||||
const watermark = {
|
||||
// 设置水印
|
||||
set: (str: string) => {
|
||||
let id = setWatermark(str);
|
||||
if (document.getElementById(id) === null) id = setWatermark(str);
|
||||
},
|
||||
// 删除水印
|
||||
del: () => {
|
||||
let id = '1.23452384164.123412416';
|
||||
if (document.getElementById(id) !== null) document.body.removeChild(<HTMLElement>document.getElementById(id));
|
||||
},
|
||||
};
|
||||
|
||||
// 导出方法
|
||||
export default watermark;
|
||||
110
web/src/utils/websocket.ts
Normal file
110
web/src/utils/websocket.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
import {ElNotification as message} from 'element-plus'
|
||||
import {Session} from "/@/utils/storage";
|
||||
import {getWsBaseURL} from "/@/utils/baseUrl";
|
||||
// @ts-ignore
|
||||
import socket from '@/types/api/socket'
|
||||
|
||||
const websocket: socket = {
|
||||
websocket: null,
|
||||
connectURL: getWsBaseURL(),
|
||||
// 开启标识
|
||||
socket_open: false,
|
||||
// 心跳timer
|
||||
hearbeat_timer: null,
|
||||
// 心跳发送频率
|
||||
hearbeat_interval: 2 * 1000,
|
||||
// 是否自动重连
|
||||
is_reonnect: true,
|
||||
// 重连次数
|
||||
reconnect_count: 3,
|
||||
// 已发起重连次数
|
||||
reconnect_current: 1,
|
||||
// 重连timer
|
||||
reconnect_timer: null,
|
||||
// 重连频率
|
||||
reconnect_interval: 5 * 1000,
|
||||
init: (receiveMessage: Function | null) => {
|
||||
if (!('WebSocket' in window)) {
|
||||
message.warning('浏览器不支持WebSocket')
|
||||
return null
|
||||
}
|
||||
const token = Session.get('token')
|
||||
if(!token){
|
||||
// message.warning('websocket认证失败')
|
||||
return null
|
||||
}
|
||||
const wsUrl = `${getWsBaseURL()}ws/${token}/`
|
||||
websocket.websocket = new WebSocket(wsUrl)
|
||||
websocket.websocket.onmessage = (e: any) => {
|
||||
if (receiveMessage) {
|
||||
receiveMessage(e)
|
||||
}
|
||||
}
|
||||
websocket.websocket.onclose = (e: any) => {
|
||||
websocket.socket_open = false
|
||||
// 需要重新连接
|
||||
if (websocket.is_reonnect) {
|
||||
websocket.reconnect_timer = setTimeout(() => {
|
||||
// 超过重连次数
|
||||
if (websocket.reconnect_current > websocket.reconnect_count) {
|
||||
clearTimeout(websocket.reconnect_timer)
|
||||
websocket.is_reonnect = false
|
||||
return
|
||||
}
|
||||
// 记录重连次数
|
||||
websocket.reconnect_current++
|
||||
websocket.reconnect()
|
||||
}, websocket.reconnect_interval)
|
||||
}
|
||||
}
|
||||
// 连接成功
|
||||
websocket.websocket.onopen = function () {
|
||||
websocket.socket_open = true
|
||||
websocket.is_reonnect = true
|
||||
// 开启心跳
|
||||
websocket.heartbeat()
|
||||
}
|
||||
// 连接发生错误
|
||||
websocket.websocket.onerror = function () { }
|
||||
},
|
||||
heartbeat: () => {
|
||||
websocket.hearbeat_timer && clearInterval(websocket.hearbeat_timer)
|
||||
|
||||
websocket.hearbeat_timer = setInterval(() => {
|
||||
let data = {
|
||||
token: Session.get('token')
|
||||
}
|
||||
websocket.send(data)
|
||||
}, websocket.hearbeat_interval)
|
||||
},
|
||||
send: (data:string, callback = null) => {
|
||||
// 开启状态直接发送
|
||||
if (websocket.websocket.readyState === websocket.websocket.OPEN) {
|
||||
websocket.websocket.send(JSON.stringify(data))
|
||||
// @ts-ignore
|
||||
callback && callback()
|
||||
} else {
|
||||
clearInterval(websocket.hearbeat_timer)
|
||||
message({
|
||||
type: 'warning',
|
||||
message: 'socket链接已断开',
|
||||
duration: 1000,
|
||||
})
|
||||
}
|
||||
},
|
||||
close: () => {
|
||||
websocket.is_reonnect = false
|
||||
websocket.websocket.close()
|
||||
websocket.websocket = null;
|
||||
},
|
||||
/**
|
||||
* 重新连接
|
||||
*/
|
||||
reconnect: () => {
|
||||
if (websocket.websocket && !websocket.is_reonnect) {
|
||||
websocket.close()
|
||||
}
|
||||
websocket.init(null)
|
||||
},
|
||||
}
|
||||
export default websocket;
|
||||
Reference in New Issue
Block a user