返回

在 vue-cli 里基于 axios 封装复用请求,提升代码可维护性

前端

前言

在现代前端开发中,向服务器发起请求获取数据或执行操作是司空见惯的事情。而 axios 是一个流行的 JavaScript 库,它可以轻松地发起 HTTP 请求,并且支持多种特性,如请求拦截器、响应拦截器、超时设置等。

然而,在实际项目中,我们经常需要对 axios 进行封装,以实现代码的复用和可维护性。本文将详细介绍如何在 vue-cli 中基于 axios 封装复用请求,以提升代码的可维护性。

一、创建通用的请求函数

首先,我们需要创建一个通用的请求函数,该函数可以接收请求参数,并返回一个 Promise 对象。我们可以将请求参数设计为一个对象,其中包含请求方法、请求 URL、请求数据、请求头等信息。

// request.js
import axios from 'axios'

export default function request(config) {
  // 请求的默认配置
  const defaultConfig = {
    method: 'get',
    url: '',
    data: {},
    headers: {}
  }

  // 合并请求参数和默认配置
  const options = Object.assign({}, defaultConfig, config)

  // 发起请求
  return axios(options)
}

二、在 Vue.js 项目中集成请求函数

接下来,我们需要在 Vue.js 项目中集成请求函数。我们可以通过在 Vue.js 实例中创建一个全局属性,来实现这一点。

// main.js
import Vue from 'vue'
import request from './request'

Vue.prototype.$request = request

现在,我们可以在 Vue.js 组件中使用 this.$request 来发起请求。

// MyComponent.vue
export default {
  methods: {
    async fetchUserData() {
      const response = await this.$request({
        method: 'get',
        url: '/api/users'
      })

      console.log(response.data)
    }
  }
}

三、封装常用的请求类型

为了进一步提高代码的可维护性,我们可以封装一些常用的请求类型,如 GETPOSTPUTDELETE 等。

// request.js
import axios from 'axios'

export default function request(config) {
  // 请求的默认配置
  const defaultConfig = {
    method: 'get',
    url: '',
    data: {},
    headers: {}
  }

  // 合并请求参数和默认配置
  const options = Object.assign({}, defaultConfig, config)

  // 发起请求
  return axios(options)
}

// 封装常用的请求类型
export const get = (url, params = {}) => {
  return request({
    method: 'get',
    url,
    params
  })
}

export const post = (url, data = {}) => {
  return request({
    method: 'post',
    url,
    data
  })
}

export const put = (url, data = {}) => {
  return request({
    method: 'put',
    url,
    data
  })
}

export const del = (url, params = {}) => {
  return request({
    method: 'delete',
    url,
    params
  })
}

现在,我们可以在 Vue.js 组件中使用这些封装好的请求类型来发起请求。

// MyComponent.vue
export default {
  methods: {
    async fetchUserData() {
      const response = await this.$request.get('/api/users')

      console.log(response.data)
    }
  }
}

四、使用请求拦截器和响应拦截器

axios 提供了请求拦截器和响应拦截器,我们可以利用它们来实现一些通用的功能,如添加请求头、处理请求错误、处理响应数据等。

// request.js
import axios from 'axios'

// 创建请求拦截器
axios.interceptors.request.use((config) => {
  // 在请求发送之前做一些事情
  return config
}, (error) => {
  // 处理请求错误
  return Promise.reject(error)
})

// 创建响应拦截器
axios.interceptors.response.use((response) => {
  // 在响应成功之后做一些事情
  return response
}, (error) => {
  // 处理响应错误
  return Promise.reject(error)
})

export default function request(config) {
  // 请求的默认配置
  const defaultConfig = {
    method: 'get',
    url: '',
    data: {},
    headers: {}
  }

  // 合并请求参数和默认配置
  const options = Object.assign({}, defaultConfig, config)

  // 发起请求
  return axios(options)
}

现在,我们可以在 Vue.js 组件中使用请求拦截器和响应拦截器来处理请求和响应。

// MyComponent.vue
export default {
  methods: {
    async fetchUserData() {
      // 在请求发送之前做一些事情
      this.$request.interceptors.request.use((config) => {
        config.headers['Authorization'] = 'Bearer ' + this.$store.getters.token
        return config
      })

      // 在响应成功之后做一些事情
      this.$request.interceptors.response.use((response) => {
        // 处理响应数据
        return response.data
      })

      const response = await this.$request.get('/api/users')

      console.log(response)
    }
  }
}

总结

本文详细介绍了如何在 vue-cli 中基于 axios 封装复用请求,以提升代码的可维护性。我们介绍了如何创建一个通用的请求函数、如何在 Vue.js 项目中集成请求函数、如何封装常用的请求类型、如何使用请求拦截器和响应拦截器。这些技术可以帮助我们更有效地使用 axios,并提高代码的可维护性和可读性。