<address id="ttjl9"></address>

      <noframes id="ttjl9"><address id="ttjl9"><nobr id="ttjl9"></nobr></address>
      <form id="ttjl9"></form>
        <em id="ttjl9"><span id="ttjl9"></span></em>
        <address id="ttjl9"></address>

          <noframes id="ttjl9"><form id="ttjl9"></form>

          Vue3中全局配置 axios 的兩種方式

          2023-2-7    前端達人

          目錄

          一、回顧 Vue2 的全局引用方式

            1. 簡單項目的全局引用

          2. 復雜項目的三步封裝

          二、Vue3 中的使用 

          1. provide/inject 方式

          2. getCurrentInstance 組合式API引入


           

           

          一、回顧 Vue2 的全局引用方式

            1. 簡單項目的全局引用

              如果只是簡單幾個頁面的使用,無需太過復雜的配置就可以直接再 main.js 中進行掛載

          
          
          1. import Vue from "vue";
          2. /* 第一步下載 axios 命令:npm i axios 或者yarn add axios 或者pnpm i axios */
          3. /* 第二步引入axios */
          4. import axios from 'axios'
          5. // 掛載一個自定義屬性$http
          6. Vue.prototype.$http = axios
          7. // 全局配置axios請求根路徑(axios.默認配置.請求根路徑)
          8. axios.defaults.baseURL = 'http://yufei.shop:3000'

             頁面使用

          
          
          1. methods:{
          2. getData(){
          3. this.$http.get('/barry').then(res=>{
          4. console.log('res',res)
          5. )}
          6. }
          7. }

          2. 復雜項目的三步封裝

            ① 新建 util/request.js (配置全局的Axios,請求攔截、響應攔截等)

                  關于 VFrame 有疑問的同學可以移步  前端不使用 il8n,如何優雅的實現多語言?

          
          
          1. import axios from "axios";
          2. import { Notification, MessageBox, Message } from "element-ui";
          3. import store from "@/store";
          4. import { getToken } from "@/utils/auth";
          5. import errorCode from "@/utils/errorCode";
          6. import Cookies from "js-cookie";
          7. import VFrame from "../framework/VFrame.js";
          8. import CONSTANT from '@/CONSTANT.js'
          9. axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
          10. // 創建axios實例
          11. const service = axios.create({
          12. // axios中請求配置有baseURL選項,表示請求URL公共部分
          13. baseURL: process.env.VUE_APP_BASE_API,
          14. // 超時
          15. timeout: 120000
          16. });
          17. // request攔截器
          18. service.interceptors.request.use(
          19. config => {
          20. // 是否需要設置 token
          21. const isToken = (config.headers || {}).isToken === false;
          22. if (getToken() && !isToken) {
          23. config.headers["Authorization"] = "Bearer " + getToken(); // 讓每個請求攜帶自定義token 請根據實際情況自行修改
          24. }
          25. var cultureName = Cookies.get(CONSTANT.UX_LANGUAGE);
          26. if (cultureName) {
          27. config.headers[CONSTANT.UX_LANGUAGE] = cultureName; // 讓每個請求攜帶自定義token 請根據實際情況自行修改
          28. }
          29. // get請求映射params參數
          30. if (config.method === "get" && config.params) {
          31. let url = config.url + "?";
          32. for (const propName of Object.keys(config.params)) {
          33. const value = config.params[propName];
          34. var part = encodeURIComponent(propName) + "=";
          35. if (value !== null && typeof value !== "undefined") {
          36. if (typeof value === "object") {
          37. for (const key of Object.keys(value)) {
          38. let params = propName + "[" + key + "]";
          39. var subPart = encodeURIComponent(params) + "=";
          40. url += subPart + encodeURIComponent(value[key]) + "&";
          41. }
          42. } else {
          43. url += part + encodeURIComponent(value) + "&";
          44. }
          45. }
          46. }
          47. url = url.slice(0, -1);
          48. config.params = {};
          49. config.url = url;
          50. }
          51. return config;
          52. },
          53. error => {
          54. console.log(error);
          55. Promise.reject(error);
          56. }
          57. );
          58. // 響應攔截器
          59. service.interceptors.response.use(
          60. res => {
          61. // 未設置狀態碼則默認成功狀態
          62. const code = res.data.code || 200;
          63. // 獲取錯誤信息
          64. const msg = errorCode[code] || res.data.msg || errorCode["default"];
          65. if (code === 401) {
          66. MessageBox.alert(
          67. VFrame.l("SessionExpired"),
          68. VFrame.l("SystemInfo"),
          69. {
          70. confirmButtonText: VFrame.l("Relogin"),
          71. type: "warning"
          72. }
          73. ).then(() => {
          74. store.dispatch("LogOut").then(() => {
          75. location.href = "/index";
          76. });
          77. });
          78. } else if (code === 500) {
          79. Message({
          80. message: msg,
          81. type: "error"
          82. });
          83. if (res.data.data) {
          84. console.error(res.data.data)
          85. }
          86. return Promise.reject(new Error(msg));
          87. } else if (code !== 200) {
          88. Notification.error({
          89. title: msg
          90. });
          91. return Promise.reject("error");
          92. } else {
          93. if (res.data.uxApi) {
          94. if (res.data.success) {
          95. return res.data.result;
          96. } else {
          97. Notification.error({ title: res.data.error });
          98. console.error(res);
          99. return Promise.reject(res.data.error);
          100. }
          101. } else {
          102. return res.data;
          103. }
          104. }
          105. },
          106. error => {
          107. console.log("err" + error);
          108. let { message } = error;
          109. if (message == "Network Error") {
          110. message = VFrame.l("TheBackEndPortConnectionIsAbnormal");
          111. } else if (message.includes("timeout")) {
          112. message = VFrame.l("TheSystemInterfaceRequestTimedOut");
          113. } else if (message.includes("Request failed with status code")) {
          114. message =
          115. VFrame.l("SystemInterface") +
          116. message.substr(message.length - 3) +
          117. VFrame.l("Abnormal");
          118. }
          119. Message({
          120. message: VFrame.l(message),
          121. type: "error",
          122. duration: 5 * 1000
          123. });
          124. return Promise.reject(error);
          125. }
          126. );
          127. export default service;

            ② 新建 api/login.js (配置頁面所需使用的 api)

          
          
          1. import request from '@/utils/request'
          2. // 登錄方法
          3. export function login(username, password,shopOrgId,counter, code, uuid) {
          4. const data = {
          5. username,
          6. password,
          7. shopOrgId,
          8. counter,
          9. uuid
          10. }
          11. return request({
          12. url: '/login',
          13. method: 'post',
          14. data: data
          15. })
          16. }
          17. // 獲取用戶詳細信息
          18. export function getInfo() {
          19. return request({
          20. url: '/getInfo',
          21. method: 'get'
          22. })
          23. }
          24. // 退出方法
          25. export function logout() {
          26. return request({
          27. url: '/logout',
          28. method: 'post'
          29. })
          30. }

            ③ 頁面使用引入

          
          
          1. import { login } from "@/api/login.js"
          2. 接下來不用多說,相信大家已經會使用了

          二、Vue3 中的使用 

           上面回顧完 Vue2 中使用 axios 我們來一起看看 Vue3 中axios的使用( 簡單Demo,前臺使用Vue3,后臺使用 node.js ),僅供學習!

          1. provide/inject 方式

              ① main.js 中 使用 provide 傳入

          
          
          1. import {
          2. createApp
          3. } from 'vue'
          4. import App from './App.vue'
          5. import router from './router'
          6. import store from './store'
          7. import "lib-flexible/flexible.js"
          8. import axios from "@/util/request.js"
          9. const app = createApp(App);
          10. app.provide('$axios', axios)
          11. app.use(store).use(router).mount('#app');

              ② 需要用到的頁面使用 inject 接受

          
          
          1. import { ref, reactive, inject, onMounted} from "vue";
          2. export default {
          3. setup() {
          4. const $axios = inject("$axios");
          5. const getData = async () => {
          6. data = await $axios({ url: "/one/data" });
          7. console.log("data", data);
          8. };
          9. onMounted(() => {
          10. getData()
          11. })
          12. return { getData }
          13. }
          14. }

          這個就是借助 provide 做一個派發,和 Vue2 中的差距使用方法差距不大 

           

          2. getCurrentInstance 組合式API引入

           ① main.js 中掛載

          
          
          1. import {
          2. createApp
          3. } from 'vue'
          4. import App from './App.vue'
          5. import router from './router'
          6. import store from './store'
          7. import "lib-flexible/flexible.js"
          8. import axios from "@/util/request.js"
          9. const app = createApp(App);
          10. /* 掛載全局對象 */
          11. app.config.globalProperties.$axios = axios;
          12. app.use(store).use(router).mount('#app');

          /* 掛載全局對象 */
          app.config.globalProperties.$axios = axios;

          重點就是上面這句

          ② 需要用的頁面使用 Composition Api -- getCurrentInstance 拿到

          
          
          1. <script>
          2. import { reactive, onMounted, getCurrentInstance } from "vue";
          3. export default {
          4. setup() {
          5. let data = reactive([]);
          6. /**
          7. * 1. 通過getCurrentInstance方法獲取當前實例
          8. * 再根據當前實例找到全局實例對象appContext,進而拿到全局實例的config.globalProperties。
          9. */
          10. const currentInstance = getCurrentInstance();
          11. const { $axios } = currentInstance.appContext.config.globalProperties;
          12. /**
          13. * 2. 通過getCurrentInstance方法獲取上下文,這里的proxy就相當于this。
          14. */
          15. const { proxy } = currentInstance;
          16. const getData = async () => {
          17. data = await $axios({ url: "/one/data" });
          18. console.log("data", data);
          19. };
          20. const getData2 = async () => {
          21. data = await proxy.$axios({ url: "/one/data" });
          22. console.log("data2", data);
          23. };
          24. onMounted(() => {
          25. getData()
          26. });
          27. return { getData };
          28. },
          29. };
          30. </script>

          下圖可以看到我們確實調用了 2次 API 

          其實通過 Composition API 中的 getCurrentInstance 方法也是有兩種方式的

           1. 通過 getCurrentInstance 方法獲取當前實例,再根據當前實例找到全局實例對象appContext,進而拿到全局實例的config.globalProperties。        

          
              
          1. const currentInstance = getCurrentInstance();
          2. const { $axios } = currentInstance.appContext.config.globalProperties;

           2. 通過getCurrentInstance方法獲取上下文,這里的proxy就相當于this。

          
              
          1. const currentInstance = getCurrentInstance();
          2. const { proxy } = currentInstance;
          3. const getData2 = async () => {
          4. data = await proxy.$axios({ url: "/one/data" });
          5. console.log("data2", data);
          6. };

           


          藍藍設計建立了UI設計分享群,每天會分享國內外的一些優秀設計,如果有興趣的話,可以進入一起成長學習,請加藍小助,微信號:ben_lanlan,報下信息,藍小助會請您入群。歡迎您加入噢~~希望得到建議咨詢、商務合作,也請與我們聯系01063334945。


          分享此文一切功德,皆悉回向給文章原作者及眾讀者.
          免責聲明:藍藍設計尊重原作者,文章的版權歸原作者。如涉及版權問題,請及時與我們取得聯系,我們立即更正或刪除。


          藍藍設計www.syprn.cn )是一家專注而深入的界面設計公司,為期望卓越的國內外企業提供卓越的UI界面設計、BS界面設計 、 cs界面設計 、 ipad界面設計 、 包裝設計 、 圖標定制 、 用戶體驗 、交互設計、 網站建設 、平面設計服務UI設計公司、界面設計公司、UI設計服務公司、數據可視化設計公司、UI交互設計公司、高端網站設計公司、UI咨詢、用戶體驗公司、軟件界面設計公司

          日歷

          鏈接

          個人資料

          藍藍設計的小編 http://www.syprn.cn

          存檔

          亚洲va欧美va天堂v国产综合