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 @   HuangBingQuan  阅读(122)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示