在Vue3腳手架中使用ts完成axios的封裝

安裝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è)分享,涉及到的原作者如果覺得被冒犯可以私聊我,我會下掉

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容