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

在vue中封装axios

时间:2023-04-01 01:24:08 vue.js

axios的基本使用1.下载axiosyarnaddaxios-Snpmiaxios-S2。Createutils/request.jsimportaxiosfrom'axios'constrequest=axios.create({baseURL:'接口的统一前缀地址'})exportdefault({method='GET',url,params,data,headers})=>{returnrequest({method,url,params,data,headers})}如果以后改库,只需要改这里,逻辑页面不用动,保证代码的复用性和独立性(高内聚低耦合)3.封装接口工具src文件下创建api/各种接口函数文件import$httpfrom'@/utils/request.js'constcustomFn=(data,params,headers)=>{//形式参数按需传入return$http({method:'defaultisGET',url:'requestaddress',data,params,headers,//按需接收})}export{customFn}//按需导出4.项目应用按需导入接口函数文件调用函数发送请求import{customFn}from'@/api/interfacefunctionfile'asyncfunctionFn(data,params,headers){//形式参数根据需要传入try{const{data:res}=awaitcustomFn(data,params,headers)//根据需要接收console.log(res)}catch(error){console.log(error)}}async和await只能接收成功状态的返回值,需要配合try-catch接收失败状态的返回值axios拦截器1.requestinterceptor//添加请求拦截器axios.interceptors.request.use(function(config){returnconfig//发送请求时的数据},function(error){//对请求错误做一些处理returnPromise.reject(error)})2.响应拦截//添加响应拦截器axios.interceptors.response.use(function(response){//当状态码以2xx/3xx开头时进入这里//对响应数据做一些事情returnresponse},function(error){//响应状态码4xx/5xxenterherereturnPromise.reject(error)})3.移除拦截器constmyInterceptors=axios.interceptors.response.use(...)axios.interceptors.response.eject(myInterceptors)