Vue3全局配置axios的兩種方式總結(jié)
前言
邊看邊學(xué)邊記錄系列,正好到 Vue3 了今天就和大家一起學(xué)習(xí)并記錄一下 Vue3 的Composition API(組合式API) 中是如何全用使用 Axios 的!
一、回顧 Vue2 的全局引用方式
1. 簡(jiǎn)單項(xiàng)目的全局引用
如果只是簡(jiǎn)單幾個(gè)頁(yè)面的使用,無(wú)需太過(guò)復(fù)雜的配置就可以直接再 main.js 中進(jìn)行掛載
import Vue from "vue"; /* 第一步下載 axios 命令:npm i axios 或者yarn add axios 或者pnpm i axios */ /* 第二步引入axios */ import axios from 'axios' // 掛載一個(gè)自定義屬性$http Vue.prototype.$http = axios // 全局配置axios請(qǐng)求根路徑(axios.默認(rèn)配置.請(qǐng)求根路徑) axios.defaults.baseURL = 'http://yufei.shop:3000'
頁(yè)面使用
methods:{
getData(){
this.$http.get('/barry').then(res=>{
console.log('res',res)
)} }
}2. 復(fù)雜項(xiàng)目的三步封裝
① 新建 util/request.js (配置全局的Axios,請(qǐng)求攔截、響應(yīng)攔截等)
關(guān)于 VFrame 有疑問(wèn)的同學(xué)可以移步 前端不使用 il8n,如何優(yōu)雅的實(shí)現(xiàn)多語(yǔ)言?
import axios from "axios";
import { Notification, MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";
import errorCode from "@/utils/errorCode";
import Cookies from "js-cookie";
import VFrame from "../framework/VFrame.js";
import CONSTANT from '@/CONSTANT.js'
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
// 創(chuàng)建axios實(shí)例
const service = axios.create({
// axios中請(qǐng)求配置有baseURL選項(xiàng),表示請(qǐng)求URL公共部分
baseURL: process.env.VUE_APP_BASE_API,
// 超時(shí)
timeout: 120000
});
// request攔截器
service.interceptors.request.use(
config => {
// 是否需要設(shè)置 token
const isToken = (config.headers || {}).isToken === false;
if (getToken() && !isToken) {
config.headers["Authorization"] = "Bearer " + getToken(); // 讓每個(gè)請(qǐng)求攜帶自定義token 請(qǐng)根據(jù)實(shí)際情況自行修改
}
var cultureName = Cookies.get(CONSTANT.UX_LANGUAGE);
if (cultureName) {
config.headers[CONSTANT.UX_LANGUAGE] = cultureName; // 讓每個(gè)請(qǐng)求攜帶自定義token 請(qǐng)根據(jù)實(shí)際情況自行修改
}
// get請(qǐng)求映射params參數(shù)
if (config.method === "get" && config.params) {
let url = config.url + "?";
for (const propName of Object.keys(config.params)) {
const value = config.params[propName];
var part = encodeURIComponent(propName) + "=";
if (value !== null && typeof value !== "undefined") {
if (typeof value === "object") {
for (const key of Object.keys(value)) {
let params = propName + "[" + key + "]";
var subPart = encodeURIComponent(params) + "=";
url += subPart + encodeURIComponent(value[key]) + "&";
}
} else {
url += part + encodeURIComponent(value) + "&";
}
}
}
url = url.slice(0, -1);
config.params = {};
config.url = url;
}
return config;
},
error => {
console.log(error);
Promise.reject(error);
}
);
// 響應(yīng)攔截器
service.interceptors.response.use(
res => {
// 未設(shè)置狀態(tài)碼則默認(rèn)成功狀態(tài)
const code = res.data.code || 200;
// 獲取錯(cuò)誤信息
const msg = errorCode[code] || res.data.msg || errorCode["default"];
if (code === 401) {
MessageBox.alert(
VFrame.l("SessionExpired"),
VFrame.l("SystemInfo"),
{
confirmButtonText: VFrame.l("Relogin"),
type: "warning"
}
).then(() => {
store.dispatch("LogOut").then(() => {
location.href = "/index";
});
});
} else if (code === 500) {
Message({
message: msg,
type: "error"
});
if (res.data.data) {
console.error(res.data.data)
}
return Promise.reject(new Error(msg));
} else if (code !== 200) {
Notification.error({
title: msg
});
return Promise.reject("error");
} else {
if (res.data.uxApi) {
if (res.data.success) {
return res.data.result;
} else {
Notification.error({ title: res.data.error });
console.error(res);
return Promise.reject(res.data.error);
}
} else {
return res.data;
}
}
},
error => {
console.log("err" + error);
let { message } = error;
if (message == "Network Error") {
message = VFrame.l("TheBackEndPortConnectionIsAbnormal");
} else if (message.includes("timeout")) {
message = VFrame.l("TheSystemInterfaceRequestTimedOut");
} else if (message.includes("Request failed with status code")) {
message =
VFrame.l("SystemInterface") +
message.substr(message.length - 3) +
VFrame.l("Abnormal");
}
Message({
message: VFrame.l(message),
type: "error",
duration: 5 * 1000
});
return Promise.reject(error);
}
);
export default service;② 新建 api/login.js (配置頁(yè)面所需使用的 api)
import axios from "axios";
import { Notification, MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";
import errorCode from "@/utils/errorCode";
import Cookies from "js-cookie";
import VFrame from "../framework/VFrame.js";
import CONSTANT from '@/CONSTANT.js'
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
// 創(chuàng)建axios實(shí)例
const service = axios.create({
// axios中請(qǐng)求配置有baseURL選項(xiàng),表示請(qǐng)求URL公共部分
baseURL: process.env.VUE_APP_BASE_API,
// 超時(shí)
timeout: 120000
});
// request攔截器
service.interceptors.request.use(
config => {
// 是否需要設(shè)置 token
const isToken = (config.headers || {}).isToken === false;
if (getToken() && !isToken) {
config.headers["Authorization"] = "Bearer " + getToken(); // 讓每個(gè)請(qǐng)求攜帶自定義token 請(qǐng)根據(jù)實(shí)際情況自行修改
}
var cultureName = Cookies.get(CONSTANT.UX_LANGUAGE);
if (cultureName) {
config.headers[CONSTANT.UX_LANGUAGE] = cultureName; // 讓每個(gè)請(qǐng)求攜帶自定義token 請(qǐng)根據(jù)實(shí)際情況自行修改
}
// get請(qǐng)求映射params參數(shù)
if (config.method === "get" && config.params) {
let url = config.url + "?";
for (const propName of Object.keys(config.params)) {
const value = config.params[propName];
var part = encodeURIComponent(propName) + "=";
if (value !== null && typeof value !== "undefined") {
if (typeof value === "object") {
for (const key of Object.keys(value)) {
let params = propName + "[" + key + "]";
var subPart = encodeURIComponent(params) + "=";
url += subPart + encodeURIComponent(value[key]) + "&";
}
} else {
url += part + encodeURIComponent(value) + "&";
}
}
}
url = url.slice(0, -1);
config.params = {};
config.url = url;
}
return config;
},
error => {
console.log(error);
Promise.reject(error);
}
);
// 響應(yīng)攔截器
service.interceptors.response.use(
res => {
// 未設(shè)置狀態(tài)碼則默認(rèn)成功狀態(tài)
const code = res.data.code || 200;
// 獲取錯(cuò)誤信息
const msg = errorCode[code] || res.data.msg || errorCode["default"];
if (code === 401) {
MessageBox.alert(
VFrame.l("SessionExpired"),
VFrame.l("SystemInfo"),
{
confirmButtonText: VFrame.l("Relogin"),
type: "warning"
}
).then(() => {
store.dispatch("LogOut").then(() => {
location.href = "/index";
});
});
} else if (code === 500) {
Message({
message: msg,
type: "error"
});
if (res.data.data) {
console.error(res.data.data)
}
return Promise.reject(new Error(msg));
} else if (code !== 200) {
Notification.error({
title: msg
});
return Promise.reject("error");
} else {
if (res.data.uxApi) {
if (res.data.success) {
return res.data.result;
} else {
Notification.error({ title: res.data.error });
console.error(res);
return Promise.reject(res.data.error);
}
} else {
return res.data;
}
}
},
error => {
console.log("err" + error);
let { message } = error;
if (message == "Network Error") {
message = VFrame.l("TheBackEndPortConnectionIsAbnormal");
} else if (message.includes("timeout")) {
message = VFrame.l("TheSystemInterfaceRequestTimedOut");
} else if (message.includes("Request failed with status code")) {
message =
VFrame.l("SystemInterface") +
message.substr(message.length - 3) +
VFrame.l("Abnormal");
}
Message({
message: VFrame.l(message),
type: "error",
duration: 5 * 1000
});
return Promise.reject(error);
}
);
export default service;③ 頁(yè)面使用引入
import { login } from "@/api/login.js"
接下來(lái)不用多說(shuō),相信大家已經(jīng)會(huì)使用了二、Vue3 中的使用
上面回顧完 Vue2 中使用 axios 我們來(lái)一起看看 Vue3 中axios的使用( 簡(jiǎn)單Demo,前臺(tái)使用Vue3,后臺(tái)使用 node.js ),僅供學(xué)習(xí)!
1. provide/inject 方式
① main.js 中 使用 provide 傳入
import {
createApp
} from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import "lib-flexible/flexible.js"
import axios from "@/util/request.js"
const app = createApp(App);
app.provide('$axios', axios)
app.use(store).use(router).mount('#app');② 需要用到的頁(yè)面使用 inject 接受
import { ref, reactive, inject, onMounted} from "vue";
export default {
setup() {
const $axios = inject("$axios");
const getData = async () => {
data = await $axios({ url: "/one/data" });
console.log("data", data);
};
onMounted(() => {
getData()
})
return { getData }
}
}這個(gè)就是借助 provide 做一個(gè)派發(fā),和 Vue2 中的差距使用方法差距不大
2. getCurrentInstance 組合式API引入
① main.js 中掛載
import {
createApp
} from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import "lib-flexible/flexible.js"
import axios from "@/util/request.js"
const app = createApp(App);
/* 掛載全局對(duì)象 */
app.config.globalProperties.$axios = axios;
app.use(store).use(router).mount('#app');/* 掛載全局對(duì)象 */
app.config.globalProperties.$axios = axios;
重點(diǎn)就是上面這句
② 需要用的頁(yè)面使用 Composition Api -- getCurrentInstance 拿到
<script>
import { reactive, onMounted, getCurrentInstance } from "vue";
export default {
setup() {
let data = reactive([]);
/**
* 1. 通過(guò)getCurrentInstance方法獲取當(dāng)前實(shí)例
* 再根據(jù)當(dāng)前實(shí)例找到全局實(shí)例對(duì)象appContext,進(jìn)而拿到全局實(shí)例的config.globalProperties。
*/
const currentInstance = getCurrentInstance();
const { $axios } = currentInstance.appContext.config.globalProperties;
/**
* 2. 通過(guò)getCurrentInstance方法獲取上下文,這里的proxy就相當(dāng)于this。
*/
const { proxy } = currentInstance;
const getData = async () => {
data = await $axios({ url: "/one/data" });
console.log("data", data);
};
const getData2 = async () => {
data = await proxy.$axios({ url: "/one/data" });
console.log("data2", data);
};
onMounted(() => {
getData()
});
return { getData };
},
};
</script>下圖可以看到我們確實(shí)調(diào)用了 2次 API

其實(shí)通過(guò) Composition API 中的 getCurrentInstance 方法也是有兩種方式的
1. 通過(guò) getCurrentInstance 方法獲取當(dāng)前實(shí)例,再根據(jù)當(dāng)前實(shí)例找到全局實(shí)例對(duì)象appContext,進(jìn)而拿到全局實(shí)例的config.globalProperties。
const currentInstance = getCurrentInstance(); const { $axios } = currentInstance.appContext.config.globalProperties;2. 通過(guò)getCurrentInstance方法獲取上下文,這里的proxy就相當(dāng)于this。
const currentInstance = getCurrentInstance(); const { proxy } = currentInstance; const getData2 = async () => { data = await proxy.$axios({ url: "/one/data" }); console.log("data2", data); };
總結(jié)
到此這篇關(guān)于Vue3全局配置axios的兩種方式的文章就介紹到這了,更多相關(guān)Vue3全局配置axios內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用vue和datatables進(jìn)行表格的服務(wù)器端分頁(yè)實(shí)例代碼
本篇文章主要介紹了使用vue和datatables進(jìn)行表格的服務(wù)器端分頁(yè)實(shí)例代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06
springboot和vue前后端交互的實(shí)現(xiàn)示例
本文主要介紹了springboot和vue前后端交互的實(shí)現(xiàn)示例,將包括一個(gè)簡(jiǎn)單的Vue.js前端應(yīng)用程序,用于發(fā)送GET請(qǐng)求到一個(gè)Spring Boot后端應(yīng)用程序,以獲取并顯示用戶列表,感興趣的可以了解一下2024-05-05
vue3點(diǎn)擊出現(xiàn)彈窗后背景變暗且不可操作的實(shí)現(xiàn)代碼
這篇文章主要介紹了vue3點(diǎn)擊出現(xiàn)彈窗后背景變暗且不可操作的實(shí)現(xiàn)代碼,本文通過(guò)實(shí)例代碼圖文相結(jié)合給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-08-08
vue深度優(yōu)先遍歷多層數(shù)組對(duì)象方式(相當(dāng)于多棵樹(shù)、三級(jí)樹(shù))
這篇文章主要介紹了vue深度優(yōu)先遍歷多層數(shù)組對(duì)象方式(相當(dāng)于多棵樹(shù)、三級(jí)樹(shù)),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08
監(jiān)聽(tīng)element-ui table滾動(dòng)事件的方法
這篇文章主要介紹了監(jiān)聽(tīng)element-ui table滾動(dòng)事件的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03

