vue封装自己的axios

在项目中封装自己的axios

  1. 在src目录下建立一个unit文件夹
  // unit => http.js
  import axios from "axios";
  
  const http = axios.create({
    baseURL: "xxxx", // 设置基础路径
    timeout: xxxx // 超时
  });

  // 请求拦截器
  http.interceptors.request.use((config)=> {
    config.headers = {
        "Content-Type": "application/json"
    }
    console.log(config);
    return config;
  })
  // 响应拦截器
  http.interceptors.response.use(msg => {
      return msg;
  });

  export default http
  1. 在src目录下建立一个api文件夹
  // src => api => a.js
  // a模块需要调用的api

  import http from "http";
  const xxx = (url, method, data)=> {
     return http({
        url,
        method,
        data
     })
  }

  export default {
    xxx
  }
  // src => api => b.js
  // b模块需要调用的api

  import http from "http";
  const xxx = (url, method, data)=> {
     return http({
        url,
        method,
        data
     })
  }

  export default {
    xxx
  }
  // src => api => index.js (管理所有页面的api,进行模块化分类)
  import a from "./a.js";
  import b from "./b.js"
  export default {
    a,
    b
  }

  1. 在main.js中把封装好的axios挂在到vue实例原型上
  import api from "@src/api/index.js"
  Vue.prototype.$api = api;
  1. 在页面中调用即可
  // a.vue
  <template></template>
  <script>
    export default {
      name: "xxx",
      data() {
        return {
          xxxx: xxxx
        }
      },
      mounted() {
        this.$api.x.xxx(url, method, data);
      }
    }
  </script>
  <style></style>
posted @ 2022-10-14 10:34  HuangBingQuan  阅读(116)  评论(0编辑  收藏  举报