專案中封裝的axios

2021-10-11 14:32:50 字數 2570 閱讀 2563

把每個一級選單按照模組去區分在urls檔案中進行統一管理

把get 和post請求進行攔截,以此進行方便頁面傳參, get和post傳參方式一樣方便使用。

main.ts中

import post from

'./apis/index'

; vue.prototype.$post = post;

// 掛載到全域性將$post

request.ts中

import axios,

from

'axios'

;import

from

'element-ui'

;// import from '@/utils/object';

// import from '@/utils/common';

import

from

'@/utils/cookieoperation'

;// import router from '../router'

const service: axiosinstance = axios.

create()

;/**

* get請求,將request中的data,包裝到url上

*/function

(originurl: string | undefined, data: any)?`;

if(data)=$

&`;}}

);} url = url.

substring(0

, url.length -1)

;return url;

}function

eachprop

(obj:object, callback:

(propname:string)

=>

void

)function

isnull

(target:any)

// request***

service.interceptors.request.

use(

(originconfig: axiosrequestconfig)

=>

else

if(method ===

'get'

)return config;

}, error => promise.

reject

(error));

// response***

service.interceptors.response.

use(

(response)

=>)}

else

if(response.data.status ===

403)

return response;},

(error)

=>,)

;// @ts-ignore

export

default service;

index.ts

import io from

'@/apis/request'

import urls,

from

'./urls'

const post: any =

// 遍歷urls檔案中所有模組

urls.

foreach

((module: postmodule)

=>

; module.urls.

foreach

((url: posturl)

=>);

});}

);/** * 介面的呼叫格式為 vue.$post.[modulename].[postname](data)

* 例如:vue.$post.user.login(data)

* 在 vue 元件中,vue 可以用 this 替代

* * 注意:需要在 main.js 中新增如下**:

* import post from '@/apis';

* vue.prototype.$post = post;

*/export

default post;

urls.ts中

export

class

posturl

}export

class

postmodule

}// 使用

const postmodule: array=[

newpostmodule

('login',''

,[newposturl

('login'

,'位址'

,'post')]

)]

.vue元件中使用

// vue檔案內應用 

this

.$post.login.

login()

.then

(res =>

)

vue專案中封裝axios

axios.defaults.timeout 100000 請求超時時間。請求位址 其實做到這裡也可以,不用去單獨封裝get post 等請求也可以直接呼叫的。然後就可以在vue頁面去呼叫了 mounted function then function response catch function...

vue專案中封裝axios

首先,配置axios 在專案src目錄下建立request.js import axios from axios import store from store import from ant design vue import from ant design vue import vue from...

vue專案中封裝axios請求

1.前言 之前是我負責這個專案的搭建,及打包上線,整個專案都是我乙個人來做,所以介面寫的遍地都是,造成了瀏覽起來很難受,不便於維護 所以就打算封裝一下axios 建立乙個apis 的js檔案來集中管理介面,走著!首先考慮的是通過promise來封裝axios,使 看起來更清晰明了 2.1 專案中引入...