Vue3全局配置axios的两种方式总结

 更新时间:2023年01月18日 10:26:58   作者:程序员啊楠  
在实际项目开发中,几乎每个组件中都会用到 axios 发起数据请求,下面这篇文章主要给大家总结介绍了关于Vue3全局配置axios的两种方式,文中通过图文介绍的非常详细,需要的朋友可以参考下

前言

边看边学边记录系列,正好到 Vue3 了今天就和大家一起学习并记录一下 Vue3 的Composition API(组合式API) 中是如何全用使用 Axios 的!

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

1. 简单项目的全局引用

如果只是简单几个页面的使用,无需太过复杂的配置就可以直接再 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)
        )}    }
}

2. 复杂项目的三步封装

① 新建 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 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;

③ 页面使用引入

import { login } from "@/api/login.js"
接下来不用多说,相信大家已经会使用了

二、Vue3 中的使用 

上面回顾完 Vue2 中使用 axios 我们来一起看看 Vue3 中axios的使用( 简单Demo,前台使用Vue3,后台使用 node.js ),仅供学习!

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');

② 需要用到的页面使用 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 中的差距使用方法差距不大 

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);
 
/* 挂载全局对象 */
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);
};

总结

到此这篇关于Vue3全局配置axios的两种方式的文章就介绍到这了,更多相关Vue3全局配置axios内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Vue.js页面验证跳转功能实现

    Vue.js页面验证跳转功能实现

    这篇文章主要介绍了Vue.js页面验证跳转功能实现,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧
    2024-04-04
  • 使用Vue构建可重用的分页组件

    使用Vue构建可重用的分页组件

    分页组件在web项目中是十分常见的组件,让我们使用Vue构建可重用的分页组件,关于基本结构和相关事件监听大家参考下本文
    2018-03-03
  • vue3学习指导教程(附带获取屏幕可视区域宽高)

    vue3学习指导教程(附带获取屏幕可视区域宽高)

    Vue3是Vue的第三个版本更快,更轻,易维护,更多的原生支持,下面这篇文章主要给大家介绍了关于vue3学习指导教程(附带获取屏幕可视区域宽高)的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2023-04-04
  • vue3 ts组合式API异常onMounted is called when there is no active component解决

    vue3 ts组合式API异常onMounted is called when&

    这篇文章主要为大家介绍了vue3 ts组合式API异常onMounted is called when there is no active component问题解决,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-05-05
  • 多个vue项目实现共用一个node-modules文件夹

    多个vue项目实现共用一个node-modules文件夹

    这篇文章主要介绍了多个vue项目实现共用一个node-modules文件夹,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-09-09
  • vue实现广告栏上下滚动效果

    vue实现广告栏上下滚动效果

    这篇文章主要介绍了vue实现广告栏上下滚动效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-11-11
  • mpvue性能优化实战技巧(小结)

    mpvue性能优化实战技巧(小结)

    这篇文章主要介绍了mpvue性能优化实战技巧(小结),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-04-04
  • Ant Design Vue Pro静态路由如何改为动态路由

    Ant Design Vue Pro静态路由如何改为动态路由

    这篇文章主要介绍了Ant Design Vue Pro静态路由如何改为动态路由问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-10-10
  • vue开发移动端底部导航条功能

    vue开发移动端底部导航条功能

    这篇文章主要介绍了vue开发移动端底部导航条功能,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-04-04
  • 简单聊聊Vue中的计算属性和属性侦听

    简单聊聊Vue中的计算属性和属性侦听

    计算属性用于处理复杂的业务逻辑,vue提供了检测数据变化的一个属性watch可以通过newVal获取变化之后的值,这篇文章主要给大家介绍了关于Vue中计算属性和属性侦听的相关资料,需要的朋友可以参考下
    2021-10-10

最新评论