axios (四)--- Axios 中的公共方法-实用的基础工具函数

本文详细介绍了axios中用于处理数据类型的多种方法,包括利用Object.prototype.toString进行类型判断,如Array、ArrayBuffer、FormData等,并提供深浅拷贝、合并对象、环境检测、字符串处理等功能。这些方法在前端开发中对于数据操作和API交互至关重要。
摘要由CSDN通过智能技术生成

axios 中的defaults 文件包含了许多公共方法👍

1、后续需要很多判断类型的,他们公共的代码就有Object.prototype.toString

判断:Array、ArrayBuffer、FormData、ArrayBuffer、object、Date、File、Blob、Function、Stream、URLSearchParams、isPlainObject

var toString = Object.prototype.toString;

/**
 * 判断是否为数组
 *
 * @param {Object} 测试的数据
 * @returns {boolean} True if value is an Array, otherwise false
 */
function isArray(val) {
  return toString.call(val) === '[object Array]';
}

/**
 * 是否为ArrayBuffer
 *
 * @param {Object} 测试的数据
 * @returns {boolean} True if value is an ArrayBuffer, otherwise false
 */
function isArrayBuffer(val) {
  return toString.call(val) === '[object ArrayBuffer]';
}

/**
 * 是否为 FormData
 *
 * @param {Object} 测试的数据
 * @returns {boolean} True if value is an FormData, otherwise false
 */
function isFormData(val) {
  return (typeof FormData !== 'undefined') && (val instanceof FormData);
}

/**
 * 是否为 ArrayBuffer
 *
 * @param {Object} 测试的数据
 * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
 */
function isArrayBufferView(val) {
  var result;
  if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
    result = ArrayBuffer.isView(val);
  } else {
    result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
  }
  return result;
}
/**
 * Determine if a value is an Object
 * @param {Object} val The value to test
 * @returns {boolean} True if value is an Object, otherwise false
 *  排除 `null`的情况
 */
function isObject(val) {
  return val !== null && typeof val === 'object';
}

/**
 * Determine if a value is a Date
 *
 * @param {Object} val The value to test
 * @returns {boolean} True if value is a Date, otherwise false
 */
function isDate(val) {
  return toString.call(val) === '[object Date]';
}

/**
 * Determine if a value is a File
 *
 * @param {Object} val The value to test
 * @returns {boolean} True if value is a File, otherwise false
 */
function isFile(val) {
  return toString.call(val) === '[object File]';
}

/**
 * Determine if a value is a Blob
 *
 * @param {Object} val The value to test
 * @returns {boolean} True if value is a Blob, otherwise false
 */
function isBlob(val) {
  return toString.call(val) === '[object Blob]';
}

/**
 * Determine if a value is a Function
 *
 * @param {Object} val The value to test
 * @returns {boolean} True if value is a Function, otherwise false
 */
function isFunction(val) {
  return toString.call(val) === '[object Function]';
}

/**
 * Determine if a value is a Stream
 *
 * @param {Object} val The value to test
 * @returns {boolean} True if value is a Stream, otherwise false
 */
function isStream(val) {
  return isObject(val) && isFunction(val.pipe);
}

/**
 * Determine if a value is a URLSearchParams object
 *
 * @param {Object} val The value to test
 * @returns {boolean} True if value is a URLSearchParams object, otherwise false
 */
function isURLSearchParams(val) {
  return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;
}


2、基本类型的判断

判断:string、number、undefined

/**
 * 是否为String
 *
 * @param {Object} val The value to test
 * @returns {boolean} True if value is a String, otherwise false
 */
function isString(val) {
  return typeof val === 'string';
}

/**
 * 是否为 Number
 *
 * @param {Object} val The value to test
 * @returns {boolean} True if value is a Number, otherwise false
 */
function isNumber(val) {
  return typeof val === 'number';
}

/**
 * 是否为undefined
 *
 * @param {Object} val The value to test
 * @returns {boolean} True if the value is undefined, otherwise false
 */
function isUndefined(val) {
  return typeof val === 'undefined';
}

3、去除首尾空格

\s是指空白,包括空格、换行、tab缩,\S 相反,^ 开始 $结束

function trim(str) {
  return str.replace(/^\s*/, '').replace(/\s*$/, '');
}

4、判断运行环境

/**
 * Determine if we're running in a standard browser environment
 * 是否运行在标准的浏览器环境
 *
 * This allows axios to run in a web worker, and react-native.
 * Both environments support XMLHttpRequest, but not fully standard globals.
 *
 * web workers:
 *  typeof window -> undefined
 *  typeof document -> undefined
 *
 * react-native:
 *  navigator.product -> 'ReactNative'
 * nativescript
 *  navigator.product -> 'NativeScript' or 'NS'
 */
function isStandardBrowserEnv() {
	// 移动端
  if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
                                           navigator.product === 'NativeScript' ||
                                           navigator.product === 'NS')) {
    return false;
  }
  return (
    typeof window !== 'undefined' &&
    typeof document !== 'undefined'
  );
}
5、forEach,可传入数组或对象,去循环并执行回调函数
typeof [1,2] === 'object' 	// true
typeof {} === 'object' 	// true
/**
 * Iterate over an Array or an Object invoking a function for each item.
 *
 * If `obj` is an Array callback will be called passing
 * the value, index, and complete array for each item.
 *(值,下标)
 * If 'obj' is an Object callback will be called passing
 * the value, key, and complete object for each property.
 *(值,键)
 * @param {Object|Array} obj The object to iterate
 * @param {Function} fn The callback to invoke for each item
 */
function forEach(obj, fn) {
  // Don't bother if no value provided,没有值跳出
  if (obj === null || typeof obj === 'undefined') {
    return;
  }
  // Force an array if not already something iterable,
  // 不是object类型则先封装成数组,typeof对数组也是返回object
  if (typeof obj !== 'object') {
    /*eslint no-param-reassign:0*/
    obj = [obj];
  }

  if (isArray(obj)) {
    // Iterate over array values
    for (var i = 0, l = obj.length; i < l; i++) {
      fn.call(null, obj[i], i, obj);
    }
  } else {
    // Iterate over object keys
    for (var key in obj) {
    // 只遍历可枚举属性
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        fn.call(null, obj[key], key, obj);
      }
    }
  }
}
6、合并对象
  Example:
  var result = merge({foo: 123}, {foo: 456});
  console.log(result.foo); // outputs 456
/**
 * Accepts varargs expecting each argument to be an object, then
 * immutably merges the properties of each object and returns result.
 *
 * When multiple objects contain the same key the later object in
 * the arguments list will take precedence.
 * 相同键的话,前面的值会被覆盖
 *
 * @param {Object} obj1 Object to merge
 * @returns {Object} Result of all merge properties
 */
function merge(/* obj1, obj2, obj3, ... */) {
  var result = {};
  function assignValue(val, key) {
    if (typeof result[key] === 'object' && typeof val === 'object') {
      result[key] = merge(result[key], val);
    } else {
      result[key] = val;
    }
  }

  for (var i = 0, l = arguments.length; i < l; i++) {
    forEach(arguments[i], assignValue);
  }
  return result;
}
7、合并深拷贝
/**
 * Function equal to merge with the difference being that no reference
 * to original objects is kept.
 *
 * @see merge
 * @param {Object} obj1 Object to merge
 * @returns {Object} Result of all merge properties
 */
function deepMerge(/* obj1, obj2, obj3, ... */) {
  var result = {};
  function assignValue(val, key) {
    if (typeof result[key] === 'object' && typeof val === 'object') {
      result[key] = deepMerge(result[key], val);
    } else if (typeof val === 'object') {
      result[key] = deepMerge({}, val);
    } else {
      result[key] = val;
    }
  }

  for (var i = 0, l = arguments.length; i < l; i++) {
    forEach(arguments[i], assignValue);
  }
  return result;
}

与上一个的区别:

let obj1 = {
	a: 1
}
let obj2 = {
	a: {d: 1, c: 3}
}
// 如果使用merge,改动合并后的对象,obj2中的也会改变
let obj3 = merge(obj1, obj2)
obj3.a = {d: 3, c: 45}
obj2.a;		// {d: 3, c: 45}
// 如果使用deepMerge,改动合并后的对象,obj2中的不会改变
let obj4 = deepMerge(obj1, obj2)
obj4.a = {d: 3, c: 45}
obj2.a;		// {d: 1, c: 3}
8、扩展
/* 
绑定函数的this
*/
module.exports = function bind(fn, thisArg) {
  return function wrap() {
    var args = new Array(arguments.length);
    for (var i = 0; i < args.length; i++) {
      args[i] = arguments[i];
    }
    return fn.apply(thisArg, args);
  };
};

/**
 * Extends object a by mutably adding to it the properties of object b.
 *
 * @param {Object} a The object to be extended
 * @param {Object} b The object to copy properties from
 * @param {Object} thisArg The object to bind function to
 * @return {Object} The resulting value of object a
 */
function extend(a, b, thisArg) {
  forEach(b, function assignValue(val, key) {
    if (thisArg && typeof val === 'function') {
      a[key] = bind(val, thisArg);
    } else {
      a[key] = val;
    }
  });
  return a;
}
9、isBuffer 判断 buffer
// 先判断不是 `undefined`和`null`
// 再判断 `val`存在构造函数,因为`Buffer`本身是一个类
// 最后通过自身的`isBuffer`方法判断

function isBuffer(val) {
  return val !== null 
          && !isUndefined(val) 
          && val.constructor !== null 
          && !isUndefined(val.constructor)
          && typeof val.constructor.isBuffer === 'function' 
          && val.constructor.isBuffer(val);
}
10、是否为纯对象

纯对象:用{}或new Object()创建的对象。

function isPlainObject(val) {
  if (Object.prototype.toString.call(val) !== '[object Object]') {
    return false;
  }

  var prototype = Object.getPrototypeOf(val);
  return prototype === null || prototype === Object.prototype;
}

例子:

// 例子1
const o = {name: 'jay}
isPlainObject(o) // true

// 例子2
const o = new Object()
o.name = 'jay'
isPlainObject(o)   // true

// 例子3
function C() {}
const c = new C()
isPlainObject(c);  // false

// 其实就是判断目标对象的原型是不是`null` 或 `Object.prototype`
npm i axios vue-axios 是一个命令,用于安装 axios 和 vue-axios 这两个包。这样做的目的是为了在你的 Vue 项目使用 axios。 在你的 main.js 文件,你需要导入 axios 和 vue-axios,并将它们与 Vue 实例绑定。可以使用以下代码实现这一点: import { createApp } from 'vue' import App from './App.vue' import router from './router' import axios from 'axios' import VueAxios from 'vue-axios' const app = createApp(App) app.use(VueAxios, axios).use(router) app.provide('axios', app.config.globalProperties.axios) app.mount('#app') 这样就可以在整个项目使用全局的 axios 对象了。 在组件,你可以通过注入(inject)的方式来使用全局的 axios。例如,在一个按钮的点击事件,你可以使用以下代码来发送 GET 请求: <button @click="getList">getList</button> <script setup> import { onMounted } from "vue"; import { inject } from "vue"; const axios = inject("axios"); function getList() { axios.get("http://x.xxx.xx.xxx:3000/getHottestArticle").then((res) => { console.log(res); }); } </script> 这样,当点击按钮时,会调用 getList 函数,并使用全局的 axios 对象发送 GET 请求。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Vue3 使用 “vue-axios](https://blog.csdn.net/qq_52697994/article/details/120210534)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值