今天,我们来总结下我们平常使用的工具函数,希望对大家有用。
1、封装fetch
源码:
/**
* 封装fetch函数,用Promise做回调
* @type {{get: (function(*=)), post: (function(*=, *=))}}
*/
const fetchUtil = {
get: (url) => {
return new Promise((resolve, reject) => {
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
}).then((response) => response.json()).then(response => {
resolve(response);
}).catch(err => {
reject(new Error(err));
});
});
},
post: (url, params) => {
return new Promise((resolve, reject) => {
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: params
}).then((response) => response.json()).then(response => {
resolve(response);
}).catch(err => {
reject(new Error(err));
});
});
}
};
export default fetchUtil;
使用:
import Fetch from "../util/FetchUtil.js";
// post请求
post(){
let params = "";
params += "phone=" + "xxxxxx" + "&password="+"123456";
Fetch.post("https://carvedu.com/api/user/sms", this.params)
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
}
// get请求
get() {
Fetch.get("https://carvedu.com/api/courses")
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
}
2、判断浏览器环境
源码:
function getSystem(){
const mac = /mac/i,
linux = /linux/i,
win = /win/i;
const platform = navigator.platform.toLowerCase();
if(mac.test(platform)){
return 'MAC';
} else if(win.test(platform)){
return 'WIN';
} else if(linux.test(platform)){
return 'Linux';
}
return undefined;
}
const browser = {
versions:function(){
let ret = 'xxSys';
const u = navigator.userAgent;
const isMobile = !!u.match(/AppleWebKit.*Mobile.*/),
ios = !!u.match(/\\(i[^;]+;( U;)? CPU.+Mac OS X/),
android = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
if(isMobile){
if(ios) return 'IOS';
if(android) return 'Android';
} else {
ret = getSystem() || ret;
}
return ret;
}(),
};
export default browser;
使用:
import browser from "../util/browers.js"
console.log(browser.versions);
3、计算时间差
源码:
let startTime = new Date().getTime();
export const start = (v) =>{
if(v==='reset'){
return startTime = new Date().getTime();
} else{
return startTime;
}
}
使用:
import {start} from "../util/Time.js"
click(){
let userTime = new Date().getTime()-start();
start('reset');
}
4、封装正则库
源码:
export default {
// 正则
regExp:()=>{
return {
mPattern :/^1[345789]\\d{9}$/, //手机号验证规则
cP : /^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$/, // 身份证验证规则
regCode : /^\\d{4}$/ //验证码规则
/*......*/
}
}
}
使用:
import regExp from '../util/regExp.js'
reg(){
var value ="" // 手机号码举例
console.log(regExp.regExp().mPattern.test(value));
},
。。。。。。。。。。。。。
作者:Vam的金豆之路
篇幅有限更多请见扩展链接:http://www.mark-to-win.com/tutorial/50912.html
本文来自投稿,不代表重蔚自留地立场,如若转载,请注明出处https://www.cwhello.com/49002.html
如有侵犯您的合法权益请发邮件951076433@qq.com联系删除