常用方法封装
1、获取cookie
export function getCookie(allCookies, name) {
const cookies = allCookies.split(‘;’);
let cookie;
cookies.map((v) => {
const value = v.trim();
if (value.indexOf(name) === 0) {
cookie = value.substring(Number(name.length) + 1, value.length);
}
return ‘-’;
});
return cookie;
}
getCookie(document.cookie, ‘XSRF-TOKEN’)
2、是否是ios环境
export function isIOS() {
return !!navigator.userAgent.match(/(i[^;]+;( U;)? CPU.+Mac OS X/); // ios终端
}
3、输入框保留小数
export function getFixed(data, fixedLength) {
if (((Math.sign(data) === 1 || Math.sign(data) === 0) && Number(data)) || data === ‘0’) {
const index = String(data).indexOf(‘.’);
if (data && index !== -1 && String(data).substring(index + 1, data.length).length > fixedLength) {
return String(data).match(^\\d+(?:\\.\\d{0,${fixedLength}})?
);
} else {
return data;
}
} else {
return isIOS() ? null : ‘’;
}
}
getFixed(value, 2)
4、 获取正整数数据(非四舍五入)
export function getParseInt(data) {
if (Number(data)) {
if (data && String(data).length > 1) {
return Math.abs(parseInt(data, 0));
} else {
return data;
}
} else {
return isIOS() ? null : ‘’;
}
}
5、数据判断是否为空,为空显示-
export function getData(res, key: DataType = ‘data’) {
if (res === 0 || res) {
switch (key) {
case ‘stringData’:
case ‘data’:
return res;
case ‘numberData’:
return Number(res);
case ‘integerData’:
return Math.round(res);
case ‘parseIntData’:
case ‘parseIntStringData’:
return Math.abs(Math.round(res)); // 获取正整数数据
case ‘abs’:
return Math.abs(res); // 绝对值数字
case ‘fixedOne’:
return Math.round(res * Math.pow(10, 1)) / Math.pow(10, 1); // 保留一位小数
case ‘fixedTwo’:
return Math.round(res * Math.pow(10, 2)) / Math.pow(10, 2); // 保留2位小数
default:
return res;
}
} else {
return key === (‘numberData’ || ‘stringData’ || ‘parseIntStringData’) ? ‘’ : ‘-’;
}
}
6、是否为非空数组
export function getMapData(data) {
if (data && Array.isArray(data) && data.length > 0) {
return data;
}
return [];
}
7、唯一标识
import { v4 as uuidv4 } from ‘uuid’;
export function getKey() {
return uuidv4();
}
8、获取路由url参数
const searchParams = new URLSearchParams(window.location.search.substring(1));
const partitionCode = searchParams.get(‘partitionCode’);
const partitionCode = decodeURIComponent(searchParams.get(‘partitionCode’));
const pageType = searchParams.get(“pageType”);
const searchParams = new URLSearchParams(window.location.hash.split(‘?’)[1]);
const loadingNo = searchParams.get(‘loadingNo’);
9、强制换行属性
overflow-wrap: break-word;// 内容将在边界内换行。如果需要,单词内部允许断行。
word-break: break-all;//强行断句,单词也可以分开