1.一键开关前端的log
let isPrintf = localStorage.getItem("printf");
export function printf(message?: string, ...optionalParams: any[]) {
if (isPrintf) {
console.log(message, ...optionalParams);
}
}
2.获取当前浏览器的设备类型,注意对普通用户有效。
//获取当前设备的类型 0:PC 1:Mobile
export function getDeviceType() {
let flag = 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 flag ? 1 : 0;
}
3.post请求,基于fetch
export async function post(url: string, query: Object) {
return fetch(url, {
method: "post",
headers: {
"Content-type": "application/json",
},
body: JSON.stringify(query),
}).then((response) => response.json());
}
4.get请求,基于fetch
export async function get(url: string) {
return fetch(url, {
method: "get",
headers: {
"Content-type": "application/json",
},
}).then(response => response.json()).catch(err => err);
}
5.格式化时间,依赖day.js
import dayjs from "dayjs";
dayjs().format();
/**
* 格式化时间
* @param timestamp
* @param formatStr "ddd, MMM D, YYYY, h:mm:ss A"|'YYYY/MM/DD HH:mm:ss'
*/
export function formatTime(timestamp: number, formatStr: string) {
if (timestamp.toString().length === 10) {
timestamp = timestamp * 1000;
}
return dayjs(timestamp).format(formatStr);
}