search
HomeWeb Front-endFront-end Q&Avue integrates axios encapsulation request

Vue’s component-based development method makes our front-end development more flexible and efficient, and in this process, data interaction with the back-end is inevitable. Axios is a good data request framework. It provides a convenient API interface, is simple to use, reliable, and easy to expand, so we chose to integrate it into the Vue project. In this article, we will introduce how to encapsulate Axios into a practical request method for easy use in Vue components.

Introduction to Axios

Generally speaking, when we use Axios to send a request, the following three steps are involved:

  1. Create an Axios instance:
// axios实例的默认配置
const instance = axios.create({
  baseURL: '',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
});
  1. Send a request:
instance.get('/api/getUser', {
  params: {
    id: 123
  }
}).then(res => {
  console.log(res)
}).catch(err => {
  console.log(err)
})
  1. Respond to the request result:
instance.interceptors.response.use(res => {
  if (res.status === 200) {
    return res.data;
  } else {
    throw new Error(res.status);
  }
}, err => {
  throw new Error(err);
})

The use of Axios is very simple and clear, but if every time When used in Vue components, these codes must be written repeatedly, which is time-consuming and error-prone. Therefore, we can encapsulate it into a general request method:

Axios request encapsulation

We can use Promise, an asynchronous programming method, to encapsulate the Axios request into a general method and then unify it Process the returned results.

import axios from 'axios';

axios.defaults.baseURL = '';
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.timeout = 5000;

// 请求拦截器
axios.interceptors.request.use(
  config => {
    // 将token添加到请求头中
    if (localStorage.getItem('accessToken')) {
      config.headers.Authorization = localStorage.getItem('accessToken');
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
axios.interceptors.response.use(
  response => {
    if (response.status === 200) {
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  error => {
    if (error.response.status) {
      switch (error.response.status) {
        case 401:
          // token过期,跳转到登录页
          break;
        case 404:
          // 请求资源不存在
          break;
        default:
          // 其他错误提示
          break;
      }
      return Promise.reject(error.response);
    }
  }
)

export default function request(options) {
  return new Promise((resolve, reject) => {
    axios(options).then(res => {
      resolve(res.data);
    }).catch(error => {
      reject(error);
    })
  })
}

In the above code, we create an Axios instance and set its default configuration, and also add request and response interceptors. In the encapsulated request method, we use Promise to return the result of the request.

  • In the request interceptor, we can add Token to the request header, or we can also customize the request here.
  • In the response interceptor, we can perform special processing on the response results, such as jumps to status code errors, resource non-existence prompts, or other error prompts, etc.

Request method usage

After encapsulating the Axios request into a general method, we can use it in the Vue component. When calling, we only need to pass the basic parameters of the request:

import request from '@/utils/request';

export function fetchData() {
  return request({
    url: '/api/list',
    method: 'get'
  })
}

Similarly, requests for HTTP methods such as GET, POST, PUT, DELETE, and PATCH are supported. Just specify different methods in the parameters.

request({
  url: '/api/user',
  method: 'post',
  data: {
    username: 'admin',
    password: '123456'
  }
});

request({
  url: '/api/user',
  method: 'put',
  params: {
    id: 123
  },
  data: {
    username: 'admin',
    password: '123456'
  }
});

request({
  url: '/api/user',
  method: 'delete',
  params: {
    id: 123
  }
});

Conclusion

This article explains in detail how to encapsulate the Axios request method through the integration and encapsulation of Axios in the Vue project. This encapsulation method can greatly reduce the amount of repeated code writing, improve development efficiency, and also facilitate the unified processing of request results. During use, we can adjust and expand its configuration and interceptors as needed to meet different needs.

The above is the detailed content of vue integrates axios encapsulation request. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
What is thedifference between class and id selector?What is thedifference between class and id selector?May 12, 2025 am 12:13 AM

Classselectorsareversatileandreusable,whileidselectorsareuniqueandspecific.1)Useclassselectors(denotedby.)forstylingmultipleelementswithsharedcharacteristics.2)Useidselectors(denotedby#)forstylinguniqueelementsonapage.Classselectorsoffermoreflexibili

CSS IDs vs Classes: The real differencesCSS IDs vs Classes: The real differencesMay 12, 2025 am 12:10 AM

IDsareuniqueidentifiersforsingleelements,whileclassesstylemultipleelements.1)UseIDsforuniqueelementsandJavaScripthooks.2)Useclassesforreusable,flexiblestylingacrossmultipleelements.

CSS: What if I use just classes?CSS: What if I use just classes?May 12, 2025 am 12:09 AM

Using a class-only selector can improve code reusability and maintainability, but requires managing class names and priorities. 1. Improve reusability and flexibility, 2. Combining multiple classes to create complex styles, 3. It may lead to lengthy class names and priorities, 4. The performance impact is small, 5. Follow best practices such as concise naming and usage conventions.

ID and Class Selectors in CSS: A Beginner's GuideID and Class Selectors in CSS: A Beginner's GuideMay 12, 2025 am 12:06 AM

ID and class selectors are used in CSS for unique and multi-element style settings respectively. 1. The ID selector (#) is suitable for a single element, such as a specific navigation menu. 2.Class selector (.) is used for multiple elements, such as unified button style. IDs should be used with caution, avoid excessive specificity, and prioritize class for improved style reusability and flexibility.

Understanding the HTML5 Specification: Key Objectives and BenefitsUnderstanding the HTML5 Specification: Key Objectives and BenefitsMay 12, 2025 am 12:06 AM

Key goals and advantages of HTML5 include: 1) Enhanced web semantic structure, 2) Improved multimedia support, and 3) Promoting cross-platform compatibility. These goals lead to better accessibility, richer user experience and more efficient development processes.

Goals of HTML5: A Developer's Guide to the Future of the WebGoals of HTML5: A Developer's Guide to the Future of the WebMay 11, 2025 am 12:14 AM

The goal of HTML5 is to simplify the development process, improve user experience, and ensure the dynamic and accessible network. 1) Simplify the development of multimedia content by natively supporting audio and video elements; 2) Introduce semantic elements such as, etc. to improve content structure and SEO friendliness; 3) Enhance offline functions through application cache; 4) Use elements to improve page interactivity; 5) Optimize mobile compatibility and support responsive design; 6) Improve form functions and simplify verification process; 7) Provide performance optimization tools such as async and defer attributes.

HTML5: Transforming the Web with New Features and CapabilitiesHTML5: Transforming the Web with New Features and CapabilitiesMay 11, 2025 am 12:12 AM

HTML5transformswebdevelopmentbyintroducingsemanticelements,multimediacapabilities,powerfulAPIs,andperformanceoptimizationtools.1)Semanticelementslike,,,andenhanceSEOandaccessibility.2)Multimediaelementsandallowdirectembeddingwithoutplugins,improvingu

ID vs. Class in CSS: A Comprehensive ComparisonID vs. Class in CSS: A Comprehensive ComparisonMay 11, 2025 am 12:12 AM

TherealdifferencebetweenusinganIDversusaclassinCSSisthatIDsareuniqueandhavehigherspecificity,whileclassesarereusableandbetterforstylingmultipleelements.UseIDsforJavaScripthooksoruniqueelements,anduseclassesforstylingpurposes,especiallywhenapplyingsty

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.