Home > Web Front-end > Vue.js > body text

Implementation and encapsulation of asynchronous requests in Vue

WBOY
Release: 2023-10-15 09:41:01
Original
1383 people have browsed it

Implementation and encapsulation of asynchronous requests in Vue

Implementation and encapsulation of asynchronous requests in Vue

In development, it is often necessary to make asynchronous requests with the back-end server to obtain data or submit data. Vue provides a simple and powerful way to handle asynchronous requests, that is, using the axios library for encapsulation.

1. Implementation of asynchronous requests
In the Vue project, asynchronous requests can be implemented by using axios in the component's methods. The following is an example of obtaining user information:

  1. First, you need to introduce the axios library into the project. You can install it through npm, or introduce it directly into the page:

    import axios from 'axios'
    Copy after login
  2. In the component's methods, write the code for the asynchronous request:

    methods: {
      getUserInfo() {
     axios.get('/api/user').then(response => {
       // 请求成功后的处理逻辑
       console.log(response.data)
     }).catch(error => {
       // 请求失败后的处理逻辑
       console.error(error)
     })
      }
    }
    Copy after login
  3. Call the getUserInfo method when the component's life cycle or event is triggered:

    created() {
      this.getUserInfo()
    }
    Copy after login

In the above code, the get method of axios is used to send a GET request. The request address is /api/user. After the request is successful, the returned data is obtained through the then method. The request fails. Then capture the error information through the catch method.

2. Encapsulation of asynchronous requests
In order to improve the reusability and maintainability of the code, asynchronous requests can be encapsulated into an independent module for use by multiple components.

  1. First, create an api.js file to encapsulate all asynchronous request methods:

    import axios from 'axios'
    
    export function getUserInfo() {
      return axios.get('/api/user')
    }
    Copy after login
  2. Introduce api.js into the component , and call the corresponding method:

    import { getUserInfo } from './api.js'
    
    methods: {
      getUser() {
     getUserInfo().then(response => {
       console.log(response.data)
     }).catch(error => {
       console.error(error)
     })
      }
    }
    Copy after login

By encapsulating all asynchronous request methods into api.js, you can directly call these methods to obtain data, avoiding duplication in each component Write the same code.

3. Use axios interceptor
In asynchronous requests, it is often necessary to perform some general processing before the request is sent or after the response is returned, such as adding request headers, modifying request parameters, and uniformly handling errors, etc. At this time, you can use the axios interceptor to achieve this.

  1. In api.js, add the following code:

    // 添加请求拦截器,设置请求头
    axios.interceptors.request.use(
      config => {
     config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('token')
     return config
      },
      error => {
     return Promise.reject(error)
      }
    )
    
    // 添加响应拦截器,统一处理错误
    axios.interceptors.response.use(
      response => {
     return response
      },
      error => {
     console.error(error)
     return Promise.reject(error)
      }
    )
    Copy after login

By adding an interceptor, you can set the request header before the request is sent. Errors are handled uniformly after the response is returned.

  1. Modify the getUserInfo method to meet the requirements of the interceptor:

    export function getUserInfo() {
      return axios.get('/api/user').then(response => {
     return response.data
      }).catch(error => {
     console.error(error)
     return Promise.reject(error)
      })
    }
    Copy after login

By using .then and .catch in the getUserInfo method, the The returned Promise object is passed to the interceptor.

Through the above steps, the encapsulation and implementation of asynchronous requests in Vue are realized. Through encapsulation, the asynchronous request code is made more concise, unified and maintainable, and it also improves the reusability of the code. At the same time, through the use of interceptors, request modifications and error handling can be easily performed before the request is sent and after the response is returned.

The above is the detailed content of Implementation and encapsulation of asynchronous requests in Vue. For more information, please follow other related articles on the PHP Chinese website!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!