ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] >[success] # 封装axios 1. 首先在 **src文件夹** 下的 **lib文件夹** 中创建 **axios.js** **src/lib/axios.js** ~~~ import axios from 'axios' import { baseURL } from '@/config' import { getToken } from '@/lib/util' class HttpRequest { constructor(baseUrl = baseURL){ // baseUrl = baseURL 是ES6的默认值写法等同于 baseUrl = baseUrl || baseURL this.baseUrl = baseUrl // this指向创建的实例,当你使用new HttpRequest创建实例时候,它会把this中定义的变量返回给你 this.queue = {} // 创建队列,每次请求都会向里面添加一个key:value,请求成功后就会去掉这个key:value,直到this.queue中没有属性值时,loading关闭 } /** * 默认options配置 */ getInsideConfig(){ const config = { baseURL: this.baseUrl, headers: { // } } return config } distroy (url) { delete this.queue[url] if (!Object.keys(this.queue).length) { // Spin.hide() } } /** * 拦截器 * @param {Object} instance - 通过axios创建的实例 * @param {String} url - 接口地址 */ interceptors(instance, url){ /** * 请求拦截器 * @param {Function} config - 请求前的控制 * @param {Function} error - 出现错误的时候会提供一个错误信息 */ instance.interceptors.request.use(config => { // 添加全局的Lodaing... if(!Object.keys(this.queue).length){ // Spin.show() } this.queue[url] = true config.headers['Authorization'] = getToken() return config }, error => { return Promise.reject(error) }) /** * 响应拦截器 * @param {Function} res - 服务端返回的东西 * @param {Function} error - 出现错误的时候会提供一个错误信息 */ instance.interceptors.response.use(res => { this.distroy(url) // 关闭全局的Lodaing... const { data } = res return data }, error => { this.distroy(url) // 关闭全局的Lodaing... return Promise.reject(error.response.data) }) } request(options){ const instance = axios.create() options = Object.assign(this.getInsideConfig(), options) // Object.assign会将2个对象合并成1个对象,相同属性值会被后者覆盖 this.interceptors(instance, options.url) // 拦截器 return instance(options) } } export default HttpRequest ~~~ **constructor方法** 是 **每一个类必须有的方法** ,如果我们不定义这个 **constructor方法** , **class类** 会默认添加一个 **空的constructor方法(例如:constructor(){})** ,在 **constructor方法** 中可以 **接收传入的参数** , 在我们 **创建实例 new HttpRequest('参数')** 时候可以 **在括号内传入参数** , 然后我们可以在 **constructor方法** 中 **对参数做一些操作** 。 2. 上面把 **baseUrl** 抽离到了 **config文件夹** 里的 **index.js 全局变量** 中 **src/config/index.js** ~~~ // 如果当前是生产环境用生产环境地址,如果是开发环境并且在vue.config.js中配置了代理,就用空字符串【''】,如果未配置代理就用开发环境地址 export const baseURL= process.env.NODE_ENV === 'production' ? 'http://production.com' : 'http://develop.com' ~~~ >[success] ## 使用方法 1. 在 **api文件夹** 中创建 **index.js** **src/api/index.js** ~~~ import HttpRequest from '@/lib/axios' const axios = new HttpRequest() export default axios ~~~ 在使用时候:我们创建一个储存用户接口的 **uesr.js** 文件 **src/api/user.js** ~~~ import axios from './index' // 获取用户信息接口 export const getUserInfo = ({ userId }) => { return axios.request({ url: '/index/getUserInfo', method: 'post', data: { userId } }) } ~~~ 然后在 **Home.vue** 页面组件中这样 **调用接口** **Home.vue** ~~~ <template> <div> <button @click="getInfo">请求数据</button> </div> </template> <script> import { getUserInfo } from '@/api/user' export default { methods: { getInfo(){ getUserInfo({ userId: 21 }).then(res => { console.log(res) }).catch(err => { console.log(err) }) } } } </script> ~~~