vue - - - - - vue3全局配置挂载axios

vue3配置axios

  • 1. 安装axios
  • 2. 配置拦截器
  • 3. vue.config.js代理配置
  • 4. 将axios全局挂载
  • 4. 文件内使用

1. 安装axios

yarn add axios

2. 配置拦截器

创建文件 /src/utils/request.js

"use strict";

import Vue from "vue";
import axios from "axios";
import { message } from "ant-design-vue";

const { baseUrl } = require("~/config"); // 全局配置的请求地址路径

let config = {
  baseURL: baseUrl,
  timeout: 60 * 1000,
  withCredentials: true,
};

const typewwwform = "application/x-www-form-urlencoded;charset=UTF-8",
  typemultipart = "multipart/form-data;charset=UTF-8",
  typejson = "application/json;charset=UTF-8";

const ShowErrorMessage = (msg = "网络错误", type = "error") => {
  message[type](msg);
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  function (config) {
    if (config.method === "post") {
      config.headers["Content-Type"] = typejson;
      return config;
    }
    return config;
  },
  function (error) {
    ShowErrorMessage(error);
    return Promise.reject(error);
  }
);

_axios.interceptors.response.use(
  function (response) {
    const { data } = response;
    if (data.ec != 200) {
      ShowErrorMessage(data.em);
    }

    if (data) return data;

    return response;
  },
  function (error) {
    ShowErrorMessage(error);
    return Promise.reject(error);
  }
);

export default _axios;

3. vue.config.js代理配置

module.exports = {
  // ......
  devServer: {
    open: true,
    port: 8080,
    host: "0.0.0.0",
    https: false,
    hotOnly: true,
    disableHostCheck: true,
    proxy: {
      "/api": {
        target: "https://***.*****.com",
        changeOrigin: true,
        ws: true,
      },
    },
  },
};

4. 将axios全局挂载

main.js

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import "./assets/sass/_init.scss";
import Api from "./utils/request.js"; // 主要是这里,引入配置好的Api

import Antd from "ant-design-vue/es";
import "ant-design-vue/dist/antd.css";

const app = createApp(App);

app.config.globalProperties.$request = Api; // 全局挂载

app.use(store).use(router).use(Antd).mount("#app");

4. 文件内使用

<template>
  <div class="index">indexdiv>
template>
<script>
import { onMounted, getCurrentInstance } from "vue";
export default {
  name: "Index",
  setup() {
    // 方式1:⬇️
    const currentInstance = getCurrentInstance(); // 获取全局实例
    const { $request } = currentInstance.appContext.config.globalProperties; // 找到挂载的axios配置
    const getUserInfo = () => {
      $request({
        url: "/api/my-info"
      }).then(res => {
        console.log("方式一 请求结果:", res);
      });
    };
    // 方式1:⬆️


    // 方式2:⬇️
    const { proxy } = getCurrentInstance();
    const getUserInfo2 = () => {
      proxy
        .$request({
          url: "/api/my-info"
        })
        .then(res => {
          console.log("方式二 请求结果:", res);
        });
    };
    // 方式2: ⬆️

    onMounted(() => {
      getUserInfo();
      getUserInfo2();
    });

    return {};
  }
};
script> 

打印结果:
vue - - - - - vue3全局配置挂载axios_第1张图片

你可能感兴趣的:(vue,vue.js)