当前位置: 首页 > Web前端 > vue.js

axios源码(5)

时间:2023-03-31 19:57:20 vue.js

今天就来看看axios的拦截器,这样在后面的核心axios构造函数中会更容易理解。拦截器也是一个构造器,然后在原型prototype中添加三个方法,分别是use,eject,forEachuse方法是添加拦截器,eject是移除拦截器,forEach是迭代拦截器。详见https://www.kancloud.cn/yunye...搜索“interceptor”为‘usestrict’;varutils=require('./../utils');functionInterceptorManager(){this.handlers=[];}/***添加一个新的拦截器到堆栈**添加一个新的拦截器到堆栈**@param{Function}fulfilled为`Promise`处理`then`的函数处理then方法*的函数@param{Function}rejected为`Promise`处理`reject`的函数处理拒绝的函数method**@return{Number}用于移除拦截器的ID稍后用于移除拦截器的id*/InterceptorManager.prototype.use=functionuse(fulfilled,rejected,options){this.handlers.push({fulfilled:fulfilled,rejected:拒绝,同步:选项?options.synchronous:false,runWhen:选项?options.runWhen:null});returnthis.handlers.length-1;};/***从堆栈中移除一个拦截器**来自从堆栈中移除拦截器**@param{Number}id`use`返回的ID上面use方法返回的id*/InterceptorManager.prototype.eject=functioneject(id){if(this.handlers[id]){this.handlers[id]=空;}};/***IterateoveralltheregisteredinterceptorsIterateoveralltheregisteredinterceptors**此方法特别适用于跳过任何*调用`eject`时可能已变为`null`的拦截器。**这个方法在跳过已经为null的拦截器时特别有用**@param{Function}fnThefunctiontocallforeachinterceptor为每个拦截器调用的函数*/InterceptorManager.prototype.forEach=functionforEach(fn){utils.forEach(this.handlers,functionforEachHandler(h){//utils文件中的forEach方法,参考axios源码(3)if(h!==null){fn(h);}});};module.exports=InterceptorManager;