Home > Web Front-end > Vue.js > Best practices for encapsulating axios in Vue

Best practices for encapsulating axios in Vue

王林
Release: 2023-06-09 16:08:41
Original
1343 people have browsed it

Vue is one of the most commonly used frameworks in front-end development, and Ajax requests are a very critical part of front-end development. In order to make it easier for developers to use, there are many practices in the Vue community that encapsulate the Ajax request library axios. This article will introduce the best practices for encapsulating axios in Vue and help you better understand how to use axios in Vue projects.

  1. Encapsulating axios

In the Vue project, we need to encapsulate axios for easy use. Here is a standard axios package:

import axios from 'axios'
import store from '@/store'
import router from '@/router'

// 创建axios实例
const service = axios.create({
  timeout: 10000, // 请求超时时间
  baseURL: process.env.VUE_APP_BASE_API // api请求的baseURL
})

// request拦截器
service.interceptors.request.use(
  config => {
    // 发送请求前进行token鉴权
    if (store.getters.token) {
      config.headers['Authorization'] = 'Bearer ' + store.getters.token
    }
    return config
  },
  error => {
    console.log(error)
    Promise.reject(error)
  }
)

// response拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 20000) {
      // 抛出异常信息
      return Promise.reject(new Error(res.message || '错误'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error)
    if (error.response.status === 401) {
      // 跳转到登录页
      router.push({ path: '/login' })
    }
    return Promise.reject(error)
  }
)

export default service
Copy after login

The above code creates an axios instance and configures the request and response interceptors. In the request interceptor, we can obtain the user token through the store and add it to the request header for authentication. In the response interceptor, we handle server response exceptions and unauthorized requests, as well as the processing of returned data.

  1. Encapsulate http requests

When using axios, we usually need to further encapsulate http requests to facilitate unified management. Below we create a wrapper for various http requests.

get request:

import http from '@/utils/http'

export default {
    get(url, params) {
        return http.get(url, {
            params: params
        })
    }
}
Copy after login

post request:

import http from '@/utils/http'

export default {
    post(url, data) {
        return http.post(url, data)
    }
}
Copy after login

delete request:

import http from '@/utils/http'

export default {
    delete(url) {
        return http.delete(url)
    }
}
Copy after login

put request:

import http from '@/utils/http'

export default {
    put(url, data) {
        return http.put(url, data)
    }
}
Copy after login

Through the above package , we can directly call the corresponding method when using http request.

  1. Using in Vue projects

To use encapsulated axios and http requests in Vue projects, you need to do the following:

First, we need Introduce axios and the encapsulated http request in the main.js file:

import axios from 'axios'
import http from '@/utils/http'

Vue.prototype.$axios = axios
Vue.prototype.$http = http
Copy after login

Secondly, use it in the component:

import api from '@/api/api'

export default {
  name: 'Demo',
  data() {
    return {
      dataList: []
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    getData() {
      let params = {
        // 请求参数
      }
      api.get('/data', params).then(res => {
        console.log(res)
        this.dataList = res.data
      })
    }
  }
}
Copy after login

Here we introduce the api-encapsulated http request and use it in the mounted life During the cycle, the getData method is called to initiate an http request, and the results are eventually displayed on the page.

  1. Conclusion

This article introduces the best practices for encapsulating axios in Vue. These practices are very good in improving development efficiency and reducing code duplication. role. For developers who are new to Vue, these techniques can be easily learned and understood, and can also play a greater role in actual development.

The above is the detailed content of Best practices for encapsulating axios in Vue. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template