untils一些公用方法:
函数防抖,倒计时,时间戳格式化,处理图片url,antd禁用日期、时间函数,下载文件,处理上传组件props,睡眠,复制功能,获取url指定参数
import moment from 'moment';
import { parse, stringify } from 'qs';
import { message } from 'antd';
import { baseImgUrl, server } from '@/config';
import Author from '@/common/author'
/* eslint no-useless-escape:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
export function isUrl(path) {
return reg.test(path);
}
export function urlToList(url) {
const urllist = url.split('/').filter(i => i);
return urllist.map((urlItem, index) => {
return `/${urllist.slice(0, index + 1).join('/')}`;
});
}
//
function getRelation(str1, str2) {
if (str1 === str2) {
console.warn('Two path are equal!'); // eslint-disable-line
}
const arr1 = str1.split('/');
const arr2 = str2.split('/');
if (arr2.every((item, index) => item === arr1[index])) {
return 1;
} else if (arr1.every((item, index) => item === arr2[index])) {
return 2;
}
return 3;
}
function getRenderArr(routes) {
let renderArr = [];
renderArr.push(routes[0]);
for (let i = 1; i < routes.length; i += 1) {
// 去重
renderArr = renderArr.filter(item => getRelation(item, routes[i]) !== 1);
// 是否包含
const isAdd = renderArr.every(item => getRelation(item, routes[i]) === 3);
if (isAdd) {
renderArr.push(routes[i]);
}
}
return renderArr;
}
export function getRoutes(path, routerData) {
let routes = Object.keys(routerData).filter(
routePath => routePath.indexOf(path) === 0 && routePath !== path
);
// Replace path to '' eg. path='user' /user/name => name
routes = routes.map(item => item.replace(path, ''));
// Get the route to be rendered to remove the deep rendering
const renderArr = getRenderArr(routes);
// Conversion and stitching parameters
const renderRoutes = renderArr.map(item => {
const exact = !routes.some(route => route !== item && getRelation(route, item) === 1);
return {
exact,
...routerData[`${path}${item}`],
key: `${path}${item}`,
path: `${path}${item}`,
};
});
return renderRoutes;
}
export function getPageQuery() {
return parse(window.location.href.split('?')[1]);
}
export function getQueryPath(path = '', query = {}) {
const search = stringify(query);
if (search.length) {
return `${path}?${search}`;
}
return path;
}
function getPageQuery1(name) {
let searchText = window.location.href.split('?')[1]
if (!searchText) return '';
let res = searchText.split('&').filter(v => {
let regExp = new RegExp('^' + name + '=')
return regExp.test(v)
})
if (!res.length) return ''
return res[0].split('=')[1]
}
/**
* 检测传进来的是否是一个object
* @param {Object} obj
*/
export function isPlainObject(obj) {
if (typeof obj !== 'object' || obj === null) return false
let proto = obj
while (Object.getPrototypeOf(proto) !== null) {
proto = Object.getPrototypeOf(proto)
}
return Object.getPrototypeOf(obj) === proto
}
export function obgParams(url = '', params) {
var s = '';
for (var key in params) {
if (params[key] !== '') {
s += "&" + key + "=" + encodeURIComponent(params[key]);
}
};
return url.indexOf('?') >= 0 ? url + s : `${url}?${s.substr(1)}`;
}
export function Copy(value, showSucess = true) {
showSucess && message.success('复制成功!');
var input = document.getElementById("input");
input.value = value; // 修改文本框的内容
input.select(); // 选中文本
document.execCommand("copy");
}
// 函数防抖
var timer = null;
var context, args, result, timestamp;
export function debounce(func, wait, immediate) {
var later = function () {
var oDate = new Date();
var last = oDate.getTime() - timestamp; // 计算第一次时间戳与当前时间戳的差值。
if (last < wait && last >= 0) { // 在等待时间内触发此函数,重新计时。
timer = setTimeout(later, wait - last);
} else {
timer = null;
if (!immediate) { // 限制immediate 为true时,执行回调函数。
result = func.apply(context, args);
if (!timer) context = args = null;
}
}
}
return function () {
var oDate = new Date();
var callNow = immediate && !timer; // 代表第一次调用立即执行。
timestamp = oDate.getTime(); // 记录下当前时间戳
context = this; // 保存上下文
args = arguments;
if (!timer) { // 第一次触发时,timer为空,进入此分支
timer = setTimeout(later, wait);
}
if (callNow) { // 第一次触发且immediate为true,进入此分支
result = func.apply(context, args);
context = args = null;
}
return result;
}
}
export function obj2params(obj) {
var result = '';
var item;
for (item in obj) {
result += '&' + item + '=' + (typeof obj[item] === 'object' ? encodeURIComponent(JSON.stringify(obj[item])) : encodeURIComponent(obj[item]));
}
return result ? result.slice(1) : result;
}
/**
* 数组元素交换位置 索引下标换
* @param {array} arr 数组
* @param {number} index1 添加项目的位置
* @param {number} index2 删除项目的位置
* index1和index2分别是两个数组的索引值,即是两个要交换元素位置的索引值,如1,5就是数组中下标为1和5的两个元素交换位置
*/
export function swapArray(arr, index1, index2) {
arr[index1] = arr.splice(index2, 1, arr[index1])[0];
return arr;
}
export function diffDate(beginTiem, endTiem) {
let diff = new Date(endTiem).getTime() - new Date(beginTiem).getTime()
let days = Math.floor(diff / (24 * 3600 * 1000));// 天
var leave1 = diff % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
var hours = Math.floor(leave1 / (3600 * 1000))
//计算相差分钟数
var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
var minutes = Math.floor(leave2 / (60 * 1000))
//计算相差秒数
var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
var seconds = Math.round(leave3 / 1000)
if (!days) {
if (!hours) {
if (!minutes) {
return seconds + "秒"
} else {
return minutes + "分钟" + seconds + "秒";
}
} else {
return hours + "小时 " + minutes + "分钟" + seconds + "秒";
}
}
return days + "天 " + hours + "小时 " + minutes + "分钟" + seconds + "秒"
}
// 格式化金额为千位分隔,不支持四舍五入
// num: 金额
// point: 小数点后几位,默认0
export function formatMoney(num, point = 0) {
let str = num * 1 ? (num * 1).toFixed(point) : (0).toFixed(point)
let re = `\\d(?=(\\d{3})+${point > 0 ? '\\.' : '$'})`
return str.replace(new RegExp(re, 'g'), $0 => $0 + ',')
}
// 时间戳格式化
export function formatTime(time, to) {
if (!time || !/[0-9]+/.test(time)) return ''
let date = new Date()
date.setTime(time)
let Y = date.getFullYear()
let M = date.getMonth() + 1
let D = date.getDate()
let h = date.getHours()
let m = date.getMinutes()
let s = date.getSeconds()
M = M < 10 ? '0' + M : M
D = D < 10 ? '0' + D : D
h = h < 10 ? '0' + h : h
m = m < 10 ? '0' + m : m
s = s < 10 ? '0' + s : s
if (to === 'm') {
return `${Y}-${M}-${D} ${h}:${m}`
} else if (to === 's') {
return `${Y}-${M}-${D} ${h}:${m}:${s}`
} else {
return `${Y}-${M}-${D}`
}
}
// 根据名称创建头像,取名称首位字符
export function createAvatar(name, size = 64) {
name = name ? name.charAt(0).toUpperCase() : ''
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
canvas.width = canvas.height = size
ctx.fillStyle = 'rgb(166,219,255)'
ctx.fillRect(0, 0, size, size)
if (name) {
ctx.fillStyle = '#fff'
ctx.font = size * 0.6 + 'px YaHei'
ctx.fillText(name, size / 2 - ctx.measureText(name).width / 2, size * 0.7)
}
return canvas.toDataURL('image/png')
}
// 图片格式处理
export function handlePicUrl(src) {
// exclude contains base64 or /static
if (src && !src.includes(';base64') && !src.includes('/static/img')) {
// if src is Array
if (src instanceof Array) {
src = src[0]
}
// if src contains commas, split the first
src = src ? src.split(',')[0] : ''
// if src does not contain ([http | https]://), splice pic server address
if (!src.match(/(http)s?:\/\//)) {
src = (baseImgUrl + src)
}
}
return src
}
// 处理禁用日期函数
export function setDisabledDate(current) {
return current && current < moment().startOf('day');
}
// 处理禁用时间函数
export function setDisabledTime(date, type) {
function range(start, end) {
const result = [];
for (let i = start; i <= end; i++) {
result.push(i);
}
return result;
};
function formatHours(date, type) {
let hour = moment().hour();
let disabledHours = [];
const chosedDate = type == "date" ? moment(date).date() : moment(date[0]).date();
if (moment().date() == chosedDate) {
disabledHours = range(0, 24).splice(0, hour);
};
return disabledHours;
};
function formatMinutes(date, type) {
let minute = moment().minute();
let disabledMinutes = [];
const chosedDate = type == "date" ? moment(date).date() : moment(date[0]).date();
if (moment().date() == chosedDate) {
disabledMinutes = range(0, 60).splice(0, minute + 1);
};
return disabledMinutes;
};
if (type === "start") {
return {
disabledHours: () => formatHours(date, 'range'),
disabledMinutes: () => formatMinutes(date, 'range'),
disabledSeconds: () => []
};
}
}
// 下载
export function downloadFile({ url, method, headers, paramName, param, fileName }) {
let fetchBody;
if (method == 'GET') {
fetchBody = fetch(`${server + url}?${paramName}=${param}`, {
method: method,
headers: headers == 'default' ? {
"content-type": "application/json",
'Authorization': Author.getToken(),
'platform': 'corp'
} : headers,
})
}
if (method == 'POST') {
fetchBody = fetch(`${server}${url}`, {
method: 'POST',
headers: {
"content-type": "application/json",
'Authorization': Author.getToken(),
'platform': 'corp'
},
body: JSON.stringify(param)
})
}
fetchBody.then(res => res.blob())
.then(data => {
let blobUrl = (window.URL || window.webkitURL || window.mozURL).createObjectURL(data)
let obj = {
a: document.createElement('a')
}
obj.a.style.display = 'none'
obj.a.href = blobUrl
obj.a.download = fileName
obj.a.click()
delete obj.a
})
}
// 处理上传文件props
export function handleUploadProps(url, name = 'file', headers = 'default', showBoolean) {
return {
action: server + url,
name: name ? name : 'file',
headers: headers == 'default' ? {
Authorization: Author.getToken(),
platform: 'corp'
} : headers,
showUploadList: showBoolean,
}
}
import { parse } from 'querystring';
import pathRegexp from 'path-to-regexp';
import { Route } from '@/models/connect';
import { message } from 'antd'
import config from '@/config';
import moment from 'moment';
import { tokenManage } from '@/constants/storageKey';
import QS from 'qs'
/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
export const isUrl = (path: string): boolean => reg.test(path);
export const getPageQuery = () => parse(window.location.href.split('?')[1]);
/**
* props.route.routes
* @param router [{}]
* @param pathname string
*/
export const getAuthorityFromRouter = <T extends Route>(
router: T[] = [],
pathname: string,
): T | undefined => {
const authority = router.find(
({ routes, path = '/' }) =>
(path && pathRegexp(path).exec(pathname)) ||
(routes && getAuthorityFromRouter(routes, pathname)),
);
if (authority) return authority;
return undefined;
};
export const getRouteAuthority = (path: string, routeData: Route[]) => {
let authorities: string[] | string | undefined;
routeData.forEach((route) => {
// match prefix
if (pathRegexp(`${route.path}/(.*)`).test(`${path}/`)) {
if (route.authority) {
authorities = route.authority;
}
// exact match
if (route.path === path) {
authorities = route.authority || authorities;
}
// get children authority recursively
if (route.routes) {
authorities = getRouteAuthority(path, route.routes) || authorities;
}
}
});
return authorities;
};
// 获取连接参数
export function getUrlSearch(search: string, name: string) {
if (!search) return '';
const paramsString = search.substring(1);
const searchParams = new URLSearchParams(paramsString);
return searchParams.get(name);
}
// 睡眠
export function sleep(duration=500){
return new Promise((resolve, reject)=>{
setTimeout(()=>{
resolve()
}, duration)
})
}
// 复制
export function Copy(value:string, showSucess=true) {
showSucess && message.success('复制成功!');
var input:any = document.createElement('input')
input.value = value;
document.body.appendChild(input)
input.select();
document.execCommand("copy");
document.body.removeChild(input)
}
// 图片格式处理
export function handlePicUrl(src: any) {
// exclude contains base64 or /static
if (src && !src.includes(';base64') && !src.includes('/static/img')) {
// if src is Array
if (src instanceof Array) {
src = src[0];
}
// if src contains commas, split the first
src = src ? src.split(',')[0] : '';
// if src does not contain ([http | https]://), splice pic server address
if (!src.match(/(http)s?:\/\//)) {
src = config.baseImgUrl + src;
}
}
return src;
}
// 处理禁用日期函数
export function setDisabledDate(current: any) {
return current && current < moment().startOf('day');
}
// 处理禁用时间函数
export function setDisabledTime(date: any, type: string) {
function range(start: any, end: any) {
const result = [];
for (let i = start; i <= end; i++) {
result.push(i);
}
return result;
};
function formatHours(date: any, type: string) {
let hour = moment().hour();
let disabledHours = [];
const chosedDate = type == "date" ? moment(date).date() : moment(date[0]).date();
if (moment().date() == chosedDate) {
disabledHours = range(0, 24).splice(0, hour);
};
return disabledHours;
};
function formatMinutes(date: any, type: string) {
let minute = moment().minute();
let disabledMinutes = [];
const chosedDate = type == "date" ? moment(date).date() : moment(date[0]).date();
if (moment().date() == chosedDate) {
disabledMinutes = range(0, 60).splice(0, minute + 1);
};
return disabledMinutes;
};
if (type === "start") {
return {
disabledHours: () => formatHours(date, 'range'),
disabledMinutes: () => formatMinutes(date, 'range'),
disabledSeconds: () => []
};
}
}
// 下载
export function downloadFile({ url, method, headers, paramName, param, fileName }: any) {
if (!url.match(/(http)s?:\/\//)) {
url = config.server + url;
}
let fetchBody: any;
if (method == 'GET') {
fetchBody = fetch(`${url}?${paramName}=${param}`, {
method: method,
headers: headers == 'default' ? {
"content-type": "application/json",
'Authorization': tokenManage.get(),
'platform': 'corp'
} : headers,
})
}
if (method == 'POST') {
fetchBody = fetch(url, {
method: 'POST',
headers: {
"content-type": "application/json",
'Authorization': tokenManage.get(),
'platform': 'corp'
},
body: JSON.stringify(param)
})
}
fetchBody.then((res: any) => res.blob())
.then((data: any) => {
let blobUrl = (window.URL || window.webkitURL).createObjectURL(data)
let obj: any = {
a: document.createElement('a')
}
obj.a.style.display = 'none'
obj.a.href = blobUrl
obj.a.download = fileName
obj.a.click()
delete obj.a
})
}
// 处理上传文件props
export function handleUploadProps(url: any, fileName:any = 'file', headers:any = 'default', showBoolean:any) {
if (!url.match(/(http)s?:\/\//)) {
url = config.server + url;
}
return {
action: url,
name: fileName,
headers: headers == 'default' ? {
Authorization: tokenManage.get(),
platform: 'corp'
} : headers,
showUploadList: showBoolean,
}
}
// 格式化金额为千位分隔,不支持四舍五入
// num: 金额
// point: 小数点后几位,默认0
export function formatMoney(num: any, point = 0) {
let str = num * 1 ? (num * 1).toFixed(point) : (0).toFixed(point)
let re = `\\d(?=(\\d{3})+${point > 0 ? '\\.' : '$'})`
return str.replace(new RegExp(re, 'g'), $0 => $0 + ',')
}
/**
* 保存 参数到url上面
* data 请求参数
*/
export function saveUrlParams(data = {}){
let query:string = QS.stringify(data);
let hash:any = location.hash || '';
hash = hash.split('?')[0] || 'hash'
window.history.replaceState('', '', `${hash}?${query}`);
}