2023-2-7 前端達人
目錄
2. getCurrentInstance 組合式API引入
如果只是簡單幾個頁面的使用,無需太過復雜的配置就可以直接再 main.js 中進行掛載
-
import Vue from "vue";
-
-
/* 第一步下載 axios 命令:npm i axios 或者yarn add axios 或者pnpm i axios */
-
/* 第二步引入axios */
-
import axios from 'axios'
-
-
-
// 掛載一個自定義屬性$http
-
Vue.prototype.$http = axios
-
// 全局配置axios請求根路徑(axios.默認配置.請求根路徑)
-
axios.defaults.baseURL = 'http://yufei.shop:3000'
-
頁面使用
-
methods:{
-
-
-
getData(){
-
-
this.$http.get('/barry').then(res=>{
-
-
console.log('res',res)
-
)}
-
}
-
-
}
① 新建 util/request.js (配置全局的Axios,請求攔截、響應攔截等)
關于 VFrame 有疑問的同學可以移步 前端不使用 il8n,如何優雅的實現多語言?
-
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";
-
// 創建axios實例
-
const service = axios.create({
-
// axios中請求配置有baseURL選項,表示請求URL公共部分
-
baseURL: process.env.VUE_APP_BASE_API,
-
// 超時
-
timeout: 120000
-
});
-
// request攔截器
-
service.interceptors.request.use(
-
config => {
-
// 是否需要設置 token
-
const isToken = (config.headers || {}).isToken === false;
-
if (getToken() && !isToken) {
-
config.headers["Authorization"] = "Bearer " + getToken(); // 讓每個請求攜帶自定義token 請根據實際情況自行修改
-
}
-
var cultureName = Cookies.get(CONSTANT.UX_LANGUAGE);
-
if (cultureName) {
-
config.headers[CONSTANT.UX_LANGUAGE] = cultureName; // 讓每個請求攜帶自定義token 請根據實際情況自行修改
-
}
-
// get請求映射params參數
-
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);
-
}
-
);
-
-
// 響應攔截器
-
service.interceptors.response.use(
-
res => {
-
// 未設置狀態碼則默認成功狀態
-
const code = res.data.code || 200;
-
// 獲取錯誤信息
-
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 (配置頁面所需使用的 api)
-
import request from '@/utils/request'
-
-
// 登錄方法
-
export function login(username, password,shopOrgId,counter, code, uuid) {
-
const data = {
-
username,
-
password,
-
shopOrgId,
-
counter,
-
uuid
-
}
-
return request({
-
url: '/login',
-
method: 'post',
-
data: data
-
})
-
}
-
-
// 獲取用戶詳細信息
-
export function getInfo() {
-
return request({
-
url: '/getInfo',
-
method: 'get'
-
})
-
}
-
-
// 退出方法
-
export function logout() {
-
return request({
-
url: '/logout',
-
method: 'post'
-
})
-
}
③ 頁面使用引入
-
import { login } from "@/api/login.js"
-
-
接下來不用多說,相信大家已經會使用了
上面回顧完 Vue2 中使用 axios 我們來一起看看 Vue3 中axios的使用( 簡單Demo,前臺使用Vue3,后臺使用 node.js ),僅供學習!
① 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');
② 需要用到的頁面使用 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 }
-
-
}
-
-
}
這個就是借助 provide 做一個派發,和 Vue2 中的差距使用方法差距不大
① 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);
-
-
/* 掛載全局對象 */
-
app.config.globalProperties.$axios = axios;
-
-
-
app.use(store).use(router).mount('#app');
/* 掛載全局對象 */
app.config.globalProperties.$axios = axios;
重點就是上面這句
② 需要用的頁面使用 Composition Api -- getCurrentInstance 拿到
-
<script>
-
import { reactive, onMounted, getCurrentInstance } from "vue";
-
export default {
-
setup() {
-
let data = reactive([]);
-
/**
-
* 1. 通過getCurrentInstance方法獲取當前實例
-
* 再根據當前實例找到全局實例對象appContext,進而拿到全局實例的config.globalProperties。
-
*/
-
const currentInstance = getCurrentInstance();
-
const { $axios } = currentInstance.appContext.config.globalProperties;
-
-
/**
-
* 2. 通過getCurrentInstance方法獲取上下文,這里的proxy就相當于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>
下圖可以看到我們確實調用了 2次 API
其實通過 Composition API 中的 getCurrentInstance 方法也是有兩種方式的
1. 通過 getCurrentInstance 方法獲取當前實例,再根據當前實例找到全局實例對象appContext,進而拿到全局實例的config.globalProperties。
const currentInstance = getCurrentInstance(); const { $axios } = currentInstance.appContext.config.globalProperties;2. 通過getCurrentInstance方法獲取上下文,這里的proxy就相當于this。
const currentInstance = getCurrentInstance(); const { proxy } = currentInstance; const getData2 = async () => { data = await proxy.$axios({ url: "/one/data" }); console.log("data2", data); };
分享此文一切功德,皆悉回向給文章原作者及眾讀者.
免責聲明:藍藍設計尊重原作者,文章的版權歸原作者。如涉及版權問題,請及時與我們取得聯系,我們立即更正或刪除。
藍藍設計( www.syprn.cn )是一家專注而深入的界面設計公司,為期望卓越的國內外企業提供卓越的UI界面設計、BS界面設計 、 cs界面設計 、 ipad界面設計 、 包裝設計 、 圖標定制 、 用戶體驗 、交互設計、 網站建設 、平面設計服務、UI設計公司、界面設計公司、UI設計服務公司、數據可視化設計公司、UI交互設計公司、高端網站設計公司、UI咨詢、用戶體驗公司、軟件界面設計公司
藍藍設計的小編 http://www.syprn.cn