专业编程基础技术教程

网站首页 > 基础教程 正文

封装几个JS实用工具函数

ccvgpt 2024-08-10 12:47:27 基础教程 9 ℃

今天,我们来总结下我们平常使用的工具函数,希望对大家有用。

1、封装fetch

「源码:」

封装几个JS实用工具函数

/**  
 * 封装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));  
},  

5、判断浏览器是否支持摄像头

「源码:」

export default {  
  // 判断有无摄像头  
    videoCheck:()=>{  
      var deviceList = [];  
      navigator.mediaDevices  
        .enumerateDevices()  
        .then(devices => {  
          devices.forEach(device => {  
            deviceList.push(device.kind);  
          });  
          if (deviceList.indexOf("videoinput") == "-1") {  
            console.info("没有摄像头");  
            return false;  
          } else {  
            console.info("有摄像头");  
          }  
        })  
        .catch(function(err) {  
          alert(err.name + ": " + err.message);  
        });  
    },  
  
}  

「使用:」

import videoCheck from '../util/videoCheck.js'  
  
videoCheck.videoCheck();  

6、图片是否加载完成

「源码:」

export default {  
    // 图片加载  
    imgLoad:(src)=>{  
      let bgImg = new Image();  
      bgImg.src = src; // 获取背景图片的url  
      bgImg.onerror = () => {  
        console.log("img onerror");  
      };  
      bgImg.onload = () => {  
        console.log("加载完成");  
        return false  
      };  
    }  
} 

「使用:」

import imgLoad from '../util/imgLoad'  
  
imgLoad.imgLoad('这里写图片的地址');  

Tags:

最近发表
标签列表