安裝axios
yarn add axios vue-axios
創(chuàng)建ts文件
在src目錄下新建utils文件夾,并在utils文件夾里創(chuàng)建三個(gè)文件
我命名分別為
- http.ts 用于對axios的請求和響應(yīng)做攔截
- request.ts 用于封裝請求方式
- api.ts 存放具體接口
代碼如下
http.ts
const baseURL = '';
import axios from 'axios'
const $http = axios.create({
//設(shè)置默認(rèn)請求地址
baseURL,
//設(shè)置請求超時(shí)時(shí)間
timeout: 5000,
//設(shè)置請求頭
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
})
// 先導(dǎo)入vuex,因?yàn)槲覀円褂玫嚼锩娴臓顟B(tài)對象
// vuex的路徑根據(jù)自己的路徑去寫
import store from '../store/index';
// 請求攔截器
$http.interceptors.request.use(config => {
// 每次發(fā)送請求之前判斷vuex中是否存在token
// 如果存在,則統(tǒng)一在http請求的header都加上token,這樣后臺根據(jù)token判斷你的登錄情況
// 即使本地存在token,也有可能token是過期的,所以在響應(yīng)攔截器中要對返回狀態(tài)進(jìn)行判斷
const token = store.state.token;
token && (config.headers.Authorization = token);
return config;
}, error => {
return console.error(error);
})
//響應(yīng)攔截
$http.interceptors.response.use(res => {
// 如果返回的狀態(tài)碼為200,說明接口請求成功,可以正常拿到數(shù)據(jù)
if (res.status === 200) {
return Promise.resolve(res);
} else {
return Promise.reject(res);
}
}, error => {
if (error.res.status) {
switch (error.res.status) {
//這里可以對響應(yīng)狀態(tài)碼進(jìn)行攔截,處理不同的狀態(tài)展示不同的交互效果
// 404請求不存在
case 404:
console.log('網(wǎng)絡(luò)請求不存在')
break;
}
return Promise.reject(error.res);
}
})
// 別忘記了
export default $http
request.ts
//導(dǎo)入request.ts 目錄下的$http
import $http from "./http";
export function get(url:string,params?:any) {
return new Promise((resolve, reject) => {
return $http({
url,
method: 'get',
data: params
}).then(res => {
resolve(res)
}).catch(error => {
reject(error)
})
})
}
api.ts
export default {
getAPI: (params?: any) => get('/api/xxx', params),
}
哪里使用哪里搬
因?yàn)檎伊税胩鞗]找到全局注冊的方法 就在具體的頁面里直接引入使用了,如果有大佬看見這個(gè)文章,請教一下全局注冊的方法,辛苦告知。
舉個(gè)例子
在HomeView.vue里使用
import { onBeforeMount } from "vue";
import getAPI from "../utils/api";
export default {
setup() {
// 接口調(diào)用
const getData = async () => {
const res = await getAPI.getAPI()
console.log(res)
}
onBeforeMount(() => {
getData()
})
return {getData}
}
}
部分內(nèi)容來自網(wǎng)絡(luò),此文章是記錄第一次使用ts封裝在vue里使用axios的方法,作為自己的一個(gè)記錄,也是給大家提供的一個(gè)分享,涉及到的原作者如果覺得被冒犯可以私聊我,我會下掉