1.httpRequest
import axios from "axios";
import $ from 'jquery';
import "jquery.cookie";
// 当需要切换使用本地后台进行调试时,需要注释掉下面这行(应该有更好实现,待研究)
// axios.defaults.baseURL = ;
axios.defaults.baseURL = ;
axios.defaults.timeout = 120*1000; // 把请求超时时间由1min改为2min(超时时间)
function getUserConfig(description) {
return {
__macAddress: $.cookie('clientSerialNo') || 'UNKNOWN',
__visitor: $.cookie('ZTEDPGSSOUser') || 'UNKNOWN',
__description: description || 'UNKNOWN'
};
}
/**
* 使用 URL 参数请求时的方法
* @param resolve
* @param reject
* @param requestFunc
* @param url
* @param prefix
* @param params
* @param headers
* @param thenHandler
* @param errHandler
* @param description
*/
function requestWithParams(
resolve, reject, requestFunc, {url, prefix, params, headers, thenHandler, errHandler, description = ''} = {}
) {
axios[requestFunc](
`${prefix}${url}`,
{
params: {...(params && typeof params === "object" ? params : {}), ...getUserConfig(description)},
headers: headers && typeof headers === "object" ? headers : {}
})
.then(res => {
if (thenHandler && typeof thenHandler === "function") {
thenHandler(res);
}
resolve(res);
})
.catch(err => {
if (errHandler && typeof errHandler === "function") {
errHandler(err);
}
reject(err);
})
}
/**
* 使用复杂参数 (body,json等) 请求时的方法
* @param resolve
* @param reject
* @param requestFunc
* @param url
* @param prefix
* @param data
* @param headers
* @param thenHandler
* @param errHandler
* @param description
*/
function requestWithData(
resolve, reject, requestFunc, {url, prefix, data, headers, thenHandler, errHandler, description = ''} = {}
) {
axios[requestFunc](
`${prefix}${url}`,
{...(data && typeof data === "object" ? data : {}), ...getUserConfig(description)},
{
headers: headers && typeof headers === "object" ? headers : {}
})
.then(res => {
if (thenHandler && typeof thenHandler === "function") {
thenHandler(res);
}
resolve(res);
})
.catch(err => {
if (errHandler && typeof errHandler === "function") {
errHandler(err);
}
reject(err);
})
}
/**
*
* @param {Object} requestConfig 包含:url, param, headers, prefix (Api 前缀) , thenHandler (then 处理方法), errHandler (error 处理方法)
* @returns {Promise<unknown>}
* @constructor
*/
export function Get({url, prefix, params, headers, thenHandler, errHandler, description = ''} = {}) {
return new Promise((resolve, reject) => requestWithParams(
resolve, reject, 'get', {url, prefix, params, headers, thenHandler, errHandler, description}
));
}
/**
*
* @param {Object} requestConfig 包含:url, param, headers, prefix (Api 前缀) , thenHandler (then 处理方法), errHandler (error 处理方法)
* @returns {Promise<unknown>}
* @constructor
*/
export function Post({url, prefix, data, headers, thenHandler, errHandler, description = ''} = {}) {
return new Promise((resolve, reject) => requestWithData(
resolve, reject, 'post', {url, prefix, data, headers, thenHandler, errHandler, description}
));
}
/**
*
* @param {Object} requestConfig 包含:url, param, headers, prefix (Api 前缀) , thenHandler (then 处理方法), errHandler (error 处理方法)
* @returns {Promise<unknown>}
* @constructor
*/
export function Put({url, prefix, data, headers, thenHandler, errHandler, description = ''} = {}) {
return new Promise((resolve, reject) => requestWithData(
resolve, reject, 'put', {url, prefix, data, headers, thenHandler, errHandler, description}
));
}
/**
*
* @param {Object} requestConfig 包含:url, data, headers, prefix (Api 前缀) , thenHandler (then 处理方法), errHandler (error 处理方法)
* @returns {Promise<unknown>}
* @constructor
*/
export function Patch({url, prefix, data, headers, thenHandler, errHandler, description = ''} = {}) {
return new Promise((resolve, reject) => requestWithData(
resolve, reject, 'patch', {url, prefix, data, headers, thenHandler, errHandler, description}
));
}
/**
*
* @param {Object} requestConfig 包含:url, param, headers, prefix (Api 前缀) , thenHandler (then 处理方法), errHandler (error 处理方法)
* @returns {Promise<unknown>}
* @constructor
*/
export function Delete({url, prefix, params, headers, thenHandler, errHandler, description = ''} = {}) {
return new Promise((resolve, reject) => requestWithParams(
resolve, reject, 'delete', {url, prefix, params, headers, thenHandler, errHandler, description}
));
}
2、时间等转换方法
// 获取月份与时间跨度列表
const getMonthList = year => {
let monthList = [];
let startTime;
let endTime;
for (let i = 1; i < 13; i++) {
let month = `${i}`.padStart(2, '0');
startTime = new Date(`${year}-${month}-01 00:00:00`).getTime()
endTime = new Date(`${year}-${month}-${getMonthDaysCount(year, i)} 24:00:00`).getTime()
monthList.push({name: `${year}年${month}月`, value: `${year}年${month}月`, timestampRange: [startTime, endTime]})
}
return monthList
}
const getYears = year => {
let currentYear = new Date().getFullYear();
let yearList = [];
for (let i = year; i <= currentYear; i++) {
yearList.push(i);
}
return yearList
}
// ms时间戳转为格式化字符串:yyyy-mm-dd hh:mm:ss
getDatestringFromTimestamp(ts) {
let d = new Date(ts);
if (d instanceof Date && !isNaN(d.getMonth())) {
return d.getFullYear() + '-' +
('0' + (d.getMonth() + 1)).slice(-2) + '-' +
('0' + d.getDate()).slice(-2) + ' ' +
('0' + d.getHours()).slice(-2) + ':' +
('0' + d.getMinutes()).slice(-2) + ':' +
('0' + d.getSeconds()).slice(-2);
} else {
// console.log(ts, ' is not a legal timestamp!');
return '1970-01-01 00:00:00';
}
},
// type: 0 -- YYYYMMDDhhmmss; 1 -- YYYYMMDD; 2 -- hhmmss
// splitters: array with 3 items, default value is ['-', ' ', ':']
getCurrentTimeString(type, splitters) {
let s = splitters && splitters.length === 3 ? splitters : ['-', ' ', ':'];
let d = new Date();
let YYYY = d.getFullYear();
let MM = ('0' + (d.getMonth() + 1)).slice(-2);
let DD = ('0' + d.getDate()).slice(-2);
let hh = ('0' + d.getHours()).slice(-2);
let mm = ('0' + d.getMinutes()).slice(-2);
let ss = ('0' + d.getSeconds()).slice(-2);
if (type === 1) {
return YYYY + s[0] + MM + s[0] + DD;
} else if (type === 2) {
return s[1] + hh + s[2] + mm + s[2] + ss;
} else {
return YYYY + s[0] + MM + s[0] + DD + s[1] + hh + s[2] + mm + s[2] + ss;
}
},
3.本地存储
export const storage = {
/**
* @function getItem
* @description 获取localStorage缓存
* @param prefix {String} 参数名前缀,一般传组件name,避免不同页面的相同参数出现缓存重名
* @param key {String} 参数名;
* @param defaultVal {String/Array} 找不到缓存参数时返回的默认值
* @param tag {Bool} ,默认为false,指定为true时表示缓存参数值为数组
* @return 找到则返回缓存值;否则若有默认值则返回默认值;否则返回null
* @author panxiancai 2022/04/02
* @example
* getItem(this.$options.name, 'name', 'Jack') // 前缀传组件name;推荐
* getItem('specific_', 'name', 'Jack') // 前缀传自定义字符串
*/
getItem(prefix, key, defaultVal, tag=false) {
let ret = tag ? JSON.parse(ls.getItem(prefix + key)) : ls.getItem(prefix + key);
return ret ? ret : (defaultVal !== undefined ? defaultVal : ret); //注意undefined判断不能省,否则传空字符也会认为false导致返回null
},
/**
* @function setItem
* @description 设置localStorage缓存
* @param prefix {String} 参数名前缀,一般传组件name,避免不同页面的相同参数出现缓存重名
* @param key {String} 参数名
* @param val {String/Array} 参数值
* @param tag {Bool} ,默认为false,指定为true时表示缓存参数值为数组
* @return 找到则返回缓存值;否则若有默认值则返回默认值;否则返回null
* @author panxiancai 2022/04/02
* @example
* setItem(this.$options.name, 'name', 'Emily') // 前缀传组件name
* setItem('specific_', 'name', 'Emily') // 前缀传自定义字符串
*/
setItem(prefix, key, val, tag=false) {
ls.setItem(prefix + key, tag ? JSON.stringify(val) : val);
},
/**
* @function removeItem
* @description 清除localStorage缓存
* @param prefix {String} 参数名前缀,一般传组件name,避免不同页面的相同参数出现缓存重名
* @param key {String} 参数名
* @return 找到则返回缓存值;否则若有默认值则返回默认值;否则返回null
* @author xushuai 2022/08/02
* @example
* removeItem(this.$options.name, 'name') // 前缀传组件name
* removeItem('specific_', 'name') // 前缀传自定义字符串
*/
removeItem(prefix, key) {
ls.removeItem(prefix + key);
}
}
4.延迟执行
/**
* 延迟执行方法
* @param val
* @param execFunc 执行方法
* @param timeOut 延迟时间,默认为 1000 毫秒
*/
lazyExecuted(val, execFunc, timeOut = 1000) {
if (this.timeoutNo) {
clearTimeout(this.timeoutNo);
}
this.timeoutNo = setTimeout(() => {
execFunc(val);
this.timeoutNo = null;
}, timeOut);
},
5、css相关
/**
* 动态添加 css 样式表
* @param styleSheet css 样式表;let styleSheet = document.styleSheets[0];
* @param selector css 选择器
* @param rules css 样式
*/
insertRule(styleSheet, selector, rules) {
if (styleSheet.insertRule) {
styleSheet.insertRule(`${selector} { ${rules} }`);
} else {
styleSheet.addRule(selector, rules);
}
},
/**
* 获取内边距 css 的上右下左详情
* @param padding
* @returns {string[]}
*/
getPaddingDetail(padding) {
padding = Array.isArray(padding) ? padding : padding.split(' ');
let top, right, bottom, left;
switch (padding.length) {
case 1:
top = right = bottom = left = padding[0];
break;
case 2:
[top, left] = padding;
bottom = top;
right = left;
break;
case 3:
[top, left, bottom] = padding;
right = left;
break;
case 4:
[top, right, bottom, left] = padding;
break;
default:
top = right = bottom = left = '0';
break;
}
return [
Number(top.replace(/[a-zA-Z]+/, '') || '0'),
Number(right.replace(/[a-zA-Z]+/, '') || '0'),
Number(bottom.replace(/[a-zA-Z]+/, '') || '0'),
Number(left.replace(/[a-zA-Z]+/, '' || '0')),
];
},
/**
* 获取两颜色区间渐变色
* @param startColor
* @param endColor
* @param segmentNumber
*/
randomColorBetween: function (startColor = '#c12e34', endColor = '#32a487', segmentNumber = 5) {
let hexToRgb = (hex, opacity = 1) => {
return {
r: parseInt('0x' + hex.slice(1, 3)),
g: parseInt('0x' + hex.slice(3, 5)),
b: parseInt('0x' + hex.slice(5, 7)),
rgb: 'rgb(' + parseInt('0x' + hex.slice(1, 3)) + ',' + parseInt('0x' + hex.slice(3, 5)) + ',' + parseInt('0x' + hex.slice(5, 7)) + ')',
rgba: 'rgba(' + parseInt('0x' + hex.slice(1, 3)) + ',' + parseInt('0x' + hex.slice(3, 5)) + ',' + parseInt('0x' + hex.slice(5, 7)) + ',' + opacity + ')',
};
};
let rgbToHex = (cl) => {
let rgb = cl.split(',');
let r = parseInt(rgb[0].split('(')[1]);
let g = parseInt(rgb[1]);
let b = parseInt(rgb[2].split(')')[0]);
return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
};
const startRGB = hexToRgb(startColor), //转换为rgb数组模式
startR = startRGB.r, startG = startRGB.g, startB = startRGB.b,
endRGB = hexToRgb(endColor),
endR = endRGB.r, endG = endRGB.g, endB = endRGB.b,
sR = (endR - startR) / segmentNumber, sG = (endG - startG) / segmentNumber,
sB = (endB - startB) / segmentNumber; //总差值
let colorSteps = [];
for (let i = 0; i < segmentNumber; i++) {
let hex = rgbToHex('rgb(' + (sR * i + startR) + ',' + (sG * i + startG) + ',' + (sB * i + startB) + ')');
colorSteps.push(hex);
}
return colorSteps;
},
/**
* 获取两颜色区间线性渐变
* @param startColor
* @param endColor
* @param segmentNumber
* @returns {*[]}
*/
linearColorBetweenWithRGB(startColor, endColor, segmentNumber = 5) {
let startDecR, startDecG, startDecB;
let endDecR, endDecG, endDecB;
if (/^#(.{2})(.{2})(.{2})$/.test(startColor)) {
[startDecR, startDecG, startDecB] = [parseInt(RegExp.$1, 16), parseInt(RegExp.$2, 16), parseInt(RegExp.$3, 16)];
}
if (/^#(.{2})(.{2})(.{2})$/.test(endColor)) {
[endDecR, endDecG, endDecB] = [parseInt(RegExp.$1, 16), parseInt(RegExp.$2, 16), parseInt(RegExp.$3, 16)];
}
let middleColorList = [];
let [stepR, stepG, stepB] = [
Math.round((endDecR - startDecR) / segmentNumber),
Math.round((endDecG - startDecG) / segmentNumber),
Math.round((endDecB - startDecB) / segmentNumber)
];
for (let i = 1; i <= segmentNumber - 2; i++) {
middleColorList.push([startDecR + stepR * i, startDecG + stepG * i, startDecB + stepB * i]);
}
return [[startDecR, startDecG, startDecB], ...middleColorList, [endDecR, endDecG, endDecB]];
},