首页 > 技术文章 > vue3 axios封装

huangtonghui 2021-12-21 19:06 原文

1、安装axios插件

"use strict";

// import Vue from "vue";
import axios from "axios";
import { createApp } from "vue";
const app = createApp({});

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  baseURL: process.env.baseURL || process.env.apiUrl || "",
  timeout: 60 * 1000, // Timeout
  withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function (response) {
    // Do something with response data
    return response;
  },
  function (error) {
    // Do something with response error
    return Promise.reject(error);
  }
);

Plugin.install = function (app) {
  // Vue.axios = _axios;
  // window.axios = _axios;
  // Object.defineProperties(Vue.prototype, {
  //   axios: {
  //     get() {
  //       return _axios;
  //     },
  //   },
  //   $axios: {
  //     get() {
  //       return _axios;
  //     },
  //   },
  // });
  app.config.globalProperties.axios = _axios;
};

app.use(Plugin);

export default Plugin;

  2、封装axios请求

import { getCurrentInstance } from "vue";

export default {
  get(url, params) {
    const { proxy } = getCurrentInstance();
    return new Promise((resolve, reject) => {
      proxy.axios.get(url, { params }).then((res) => {
        try {
          resolve(res.data);
        } catch (error) {
          reject(error);
        }
      });
    });
  },
  post(url, params) {
    const { proxy } = getCurrentInstance();
    return new Promise((resolve, reject) => {
      proxy.axios.get(url, params).then((res) => {
        try {
          resolve(res.data);
        } catch (error) {
          reject(error);
        }
      });
    });
  },
};

  3、创建api接口

import http from '../plugins/http'

export default {
  getList: (p) => http.get("/api/user", p),
};

  4、调用api接口

import apis from './apis'
export default {
  created() {
    apis.getList({a:123}).then((res) => {
      console.log('res: ', res);
    });
  },
};

  5、mock接口

import "./plugins/axios";
import { createApp } from "vue";
import App from "./App.vue";
import "./registerServiceWorker";
import router from "./router";
import store from "./store";
import http from './plugins/axios'
import mock from '../mock'

createApp(App).use(store).use(router).use(http).use(mock).mount("#app");

  6、配置跨域,根目录创建vue.config.js

module.exports = {
  devServer: {
    port: '8080',
    open: true,
    proxy: {
      '/api': {
        target: '',
        changeOrigin: true,
        pathRewrite: {'^/api': ''}
      }
    }
  }
}

  

推荐阅读