今天,我們來總結(jié)下我們平常使用的工具函數(shù),希望對大家有用。1、封裝fetch源碼:/** * 封裝fetch函數(shù),用Promise做回調(diào) * @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、判斷瀏覽器環(huán)境源碼: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、計(jì)算時間差源碼: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}$/, //手機(jī)號驗(yàn)證規(guī)則 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]$/, // 身份證驗(yàn)證規(guī)則 regCode : /^d{4}$/ //驗(yàn)證碼規(guī)則 /*……*/ } }}使用:import regExp from ‘../util/regExp.js’reg(){ var value =”” // 手機(jī)號碼舉例 console.log(regExp.regExp().mPattern.test(value));},
。。。。。。。。。。。。。
作者:Vam的金豆之路
篇幅有限更多請見擴(kuò)展鏈接:http://www.mark-to-win.com/tutorial/50912.html