1. 获取地址栏参数
function getQuery(key) {
letparams = window.location.href.split("?")[1];
params = params ? params.split("&") : [];
let val = (params.filter(item => item.indexOf(key) !== -1))[0];
return val ? val.split("=")[1] : false;
}
2. localStorage
function getLocalStorage(key) {
let val = key ? window.localStorage.getItem(key) : '';
return val ? JSON.parse(val) : false;
}
function setLocalStorage(key, val) {
if(key) window.localStorage.setItem(key, JSON.stringify(val || ''));
}
3. sessionStorage
export const setSession = (key: string, value: any) => {
window.sessionStorage.setItem(key, JSON.stringify(value));
}
export const getSession = <T>(key: string): T | null => {
const value: string | null = window.sessionStorage.getItem(key);
const result: T | null = value ? JSON.parse(value) : null;
return result;
}
export const removeSession = (key: string) => {
window.sessionStorage.removeItem(key);
}
4. 检查手机号
function checkPhone(phone) {
const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
return reg.test(phone);
}
5. 复制文字
function copyFun(text) {
var input = document.createElement("input"); // 直接构建input
input.value = text; // 设置内容
document.body.appendChild(input); // 添加临时实例
input.select(); // 选择实例内容
document.execCommand("Copy"); // 执行复制
document.body.removeChild(input); // 删除临时实例
alert("复制成功");
}
6. 获取当天日期
export const getCurrentDate = (isHour?: boolean, val?: Date) => {
const date = val || new Date();
const year = date.getFullYear();
let month: any = date.getMonth() + 1;
let day: any = date.getDate();
let hour: any = date.getHours();
let min: any = date.getMinutes();
let sec: any = date.getSeconds();
if(month < 10) month = '0' + month;
if(day < 10) day = '0' + day;
if(min < 10) min = '0' + min;
if(hour < 10) hour = '0' + hour;
if(sec < 10) sec = '0' + sec;
if(isHour) {
return `${year}-${month}-${day} ${hour}:${min}:${sec}`;
} else {
return `${year}-${month}-${day}`;
}
}
7. txt导出
export const exportRaw = (name, data) => {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(data));
element.setAttribute('download', name);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
alert("导出成功");
}
8. 判断是否是微信浏览器
export const isWeixinBrowser = () => {
let ua = navigator.userAgent.toLowerCase();
return /micromessenger/.test(ua) ? true : false;
}
9. 判断是否是手机浏览器
export const isMobile = () => {
let userAgentInfo = navigator.userAgent;
let Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod'];
let getArr = Agents.filter(i => userAgentInfo.includes(i));
return getArr.length ? true : false;
}
10. 浮点数相乘,处理精度丢失
export const numMulti = (num1, num2) => {
var baseNum = 0;
try {
baseNum += num1.toString().split(".")[1].length;
} catch (e) {}
try {
baseNum += num2.toString().split(".")[1].length;
} catch (e) {}
return Number(num1.toString().replace(".", "")) * Number(num2.toString().replace(".", "")) / Math.pow(10, baseNum);
};
11. 获取IP、省市等信息
function getCity() {
$.ajax({
url: `https://ipservice.ws.126.net/locate/api/getLocByIp?callback=loc0`,
type: 'GET',
dataType: 'jsonp'
});
}
function loc0(res) {
console.log(res.result);
}
12. npm和yarn设置淘宝镜像源
npm config set registry https://registry.npm.taobao.org
yarn config set registry http://registry.npm.taobao.org
13. axios JSONP请求(ts版)
declare interface Window<T> {
[key: string]: T
}
const requestJsonp = <T>(url: string, callback: string): Promise<T> => {
return new Promise((resolve, _) => {
window[callback] = (res: T) => resolve(res)
const JSONP = document.createElement('script');
JSONP.type = 'text/javascript';
JSONP.src = url;
document.getElementsByTagName('head')[0].appendChild(JSONP);
setTimeout(() => {
document.getElementsByTagName('head')[0].removeChild(JSONP)
},500)
})
}
requestJsonp('https://api?callback=testfunc', 'testfunc').then(res => {}).catch(err => {});
14. 字符串全部替换(replaceAll)
const escapeRegExp = (string: string) => {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
export const replaceAll = (str: string, match: string, replacement: string) => {
return str.replace(new RegExp(escapeRegExp(match), 'g'), () => replacement);
}
15. 生成UUID
export const createUUID = (): string => {
var result: any = [];
var hexDigits = "0123456789abcdef";
for (var i = 0; i < 36; i++) {
result[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
} // bits 12-15 of the time_hi_and_version field to 0010
result[14] = "4"; // bits 6-7 of the clock_seq_hi_and_reserved to 01
result[19] = hexDigits.substr(result[19] & 0x3 | 0x8, 1);
result[8] = result[13] = result[18] = result[23] = "-";
return result.join("");
}
16. vue3图片动态引入
export const getImgUrl = (name: string) => {
return new URL(`../assets/image/${name}`, import.meta.url).href
}