Home Web Front-end JS Tutorial How to use Vue to secondary encapsulate the axios plug-in

How to use Vue to secondary encapsulate the axios plug-in

May 28, 2018 pm 03:01 PM
axios secondary encapsulation

This time I will show you how to use Vue to re-encapsulate the axios plug-in. What are the precautions for using Vue to re-encapsulate the axios plug-in? The following is a practical case, let's take a look.

No matter what method is used to obtain data, for a project, the code must be easy to maintain and secondly, it must be written beautifully, so adding a layer of encapsulation is necessary

vuejs2.0 vue-resource is no longer maintained, vuejs2.0 has used axios, which is the main reason why I will switch to axios, without further ado:

Basic packaging requirements:

  1. Unified url configuration

  2. Unified api request

  3. request (request) interceptor, for example : Bring token, etc., set request header

  4. ##response (response) interceptor, for example: unified
  5. error handling

    , page redirection, etc.

  6. As needed, combine Vuex to do global loading animation, or error handling
  7. Encapsulate axios into a Vue plug-in and use it
File structure

Use vue-cli for related encapsulation, in the src folder:

src
  |
-- http 封装axios模块文件夹
   |
---- config.js axios的默认配置
---- api.js 二次封装axios,拦截器等
---- interface.js 请求接口文件
---- index.js 将axios封装成插件
Copy after login

config.js

The default configuration refers to gitHub. The following is just an example:

export default {
  method: 'post',
  // 基础url前缀
  baseURL: 'https://easy-mock.com/mock/5ad75e9f41d4d65f0e935be4/example',
  // 请求头信息
  headers: {
   'Content-Type':'application/json;charset=UTF-8'
  },
  // 参数
  data: {},
  // 设置超时时间
  timeout: 10000,
  // 携带凭证
  withCredentials: false,
  // 返回数据类型
  responseType: 'json'
}
Copy after login

PS: Here is a Mock tool Easy Mock recommended. The above request address comes from this tool. I will write about how to use this tool separately when I have time in the future.

api.js

import axios from 'axios' // 注意先安装哦
import config from './config.js' // 倒入默认配置
import qs from 'qs' // 序列化请求数据,视服务端的要求
export default function $axios (options) {
  return new Promise((resolve, reject) => {
    const instance = axios.create({
      baseURL: config.baseURL,
      headers: {},
      transformResponse: [function (data) {}]
    }
  )
  // request 拦截器
  instance.interceptors.request.use(
    config => {
      // Tip: 1
      // 请求开始的时候可以结合 vuex 开启全屏的 loading 动画
      // Tip: 2 
      // 带上 token , 可以结合 vuex 或者重 localStorage
      // if (store.getters.token) {
      //   config.headers['X-Token'] = getToken() // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
      // } else {
      //   // 重定向到登录页面  
      // }
      // Tip: 3
      // 根据请求方法,序列化传来的参数,根据后端需求是否序列化
      if (config.method.toLocaleLowerCase() === 'post' 
        || config.method.toLocaleLowerCase() === 'put' 
        || config.method.toLocaleLowerCase() === 'delete') {
        config.data = qs.stringify(config.data)
      }
      return config
    },
    error => {
      // 请求错误时做些事(接口错误、超时等)
      // Tip: 4
      // 关闭loadding
      console.log('request:', error) 
    
      // 1.判断请求超时
      if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
        console.log('根据你设置的timeout/真的请求超时 判断请求现在超时了,你可以在这里加入超时的处理方案')
        // return service.request(originalRequest);//例如再重复请求一次
      }
      // 2.需要重定向到错误页面
      const errorInfo = error.response
      console.log(errorInfo)
      if (errorInfo) {
        // error =errorInfo.data//页面那边catch的时候就能拿到详细的错误信息,看最下边的Promise.reject
        const errorStatus = errorInfo.status; // 404 403 500 ... 等
        router.push({
          path: `/error/${errorStatus}`
        })
      }
      return Promise.reject(error) // 在调用的那边可以拿到(catch)你想返回的错误信息
    }
  )
 
  // response 拦截器
  instance.interceptors.response.use(
    response => {
      let data;
      // IE9时response.data是undefined,因此需要使用response.request.responseText(Stringify后的字符串)
      if(response.data == undefined){
        data = response.request.responseText
      } else{
        data = response.data
      }
      // 根据返回的code值来做不同的处理(和后端约定)
      switch (data.code) {
        case '':
        break;
        default:
      }
      // 若不是正确的返回code,且已经登录,就抛出错误
      // const err = new Error(data.description)
      // err.data = data
      // err.response = response
      // throw err
      return data
    },
    err => {
      if (err && err.response) {
        switch (err.response.status) {
          case 400:
          err.message = '请求错误'
          break
      
          case 401:
          err.message = '未授权,请登录'
          break
      
          case 403:
          err.message = '拒绝访问'
          break
      
          case 404:
          err.message = `请求地址出错: ${err.response.config.url}`
          break
      
          case 408:
          err.message = '请求超时'
          break
      
          case 500:
          err.message = '服务器内部错误'
          break
      
          case 501:
          err.message = '服务未实现'
          break
      
          case 502:
          err.message = '网关错误'
          break
      
          case 503:
          err.message = '服务不可用'
          break
      
          case 504:
          err.message = '网关超时'
          break
      
          case 505:
          err.message = 'HTTP版本不受支持'
          break
      
          default:
        }
      }
      console.error(err)
      // 此处我使用的是 element UI 的提示组件
      // Message.error(`ERROR: ${err}`);
      return Promise.reject(err) // 返回接口返回的错误信息
    }
  )
 
  //请求处理
  instance(options)
    .then((res) => {
      resolve(res)
      return false
    })
    .catch((error) => {
      reject(error)
    })
  })
}
Copy after login

interface.js

import axios from './api' // 倒入 api
/* 将所有接口统一起来便于维护
 * 如果项目很大可以将 url 独立成文件,接口分成不同的模块
 * 此处的数据依然来自 Easy Mock
 */
// 单独倒出
export const query = params => {
  return axios({
    url: '/query',
    method: 'get',
    params
  })
}
 
export const mock = params => {
  return axios({
    url: '/mock',
    method: 'get',
    params
  })
}
export const upload = data => {
  return axios({
    url: '/upload',
    method: 'post',
    data
  })
}
// 默认全部倒出
// 根绝需要进行 
export default {
  query,
  mock,
  upload
}
Copy after login

index.js

Encapsulated into a Vue plug-in, it can be (raised) in (high) used (B) used (grid)

// 倒入所有接口
import apiList from './interface'
const install = Vue => {
  if (install.installed) 
    return;
  install.installed = true;
  Object.defineProperties(Vue.prototype, {
    // 注意哦,此处挂载在 Vue 原型的 $api 对象上
    $api: {
      get() {
        return apiList
      }
    }
  })
}
export default install
Copy after login

Used

So far, everything is ready It’s almost ready for use. Do the following operations in mian.js:

// 倒入 http 文件夹下的 index.js
import api from './http/index'
Vue.use(api)
// 此时可以直接在 Vue 原型上调用 $api 了
Copy after login

Summary

    The above secondary encapsulation is relatively comprehensive and basically completed. In order to meet our previous needs
  1. In terms of error handling, we also need to agree on the return value with the backend and make specific agreements
  2. Encapsulation callback It’s a bit much. When using it, you also need to add then() to process the results. Learn about async & await. Of course, good things must be hidden. I won’t share them...
  3. PS: IE9 does not support Promise. You need to install a polyfill
import 'babel-polyfill'
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to use the parent-child component in Vue to communicate with the todolist component


How to use Vue to integrate the AdminLTE template

The above is the detailed content of How to use Vue to secondary encapsulate the axios plug-in. For more information, please follow other related articles on the PHP Chinese website!

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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Choice of data request in Vue: Axios or Fetch? Choice of data request in Vue: Axios or Fetch? Jul 17, 2023 pm 06:30 PM

Choice of data request in Vue: AxiosorFetch? In Vue development, handling data requests is a very common task. Choosing which tool to use for data requests is a question that needs to be considered. In Vue, the two most common tools are Axios and Fetch. This article will compare the pros and cons of both tools and give some sample code to help you make your choice. Axios is a Promise-based HTTP client that works in browsers and Node.

Efficiently utilize Vue and Axios to implement batch processing of front-end data Efficiently utilize Vue and Axios to implement batch processing of front-end data Jul 17, 2023 pm 10:43 PM

Efficiently utilize Vue and Axios to implement batch processing of front-end data. In front-end development, data processing is a common task. When we need to process a large amount of data, processing the data will become very cumbersome and inefficient if there is no effective method. Vue is an excellent front-end framework, and Axios is a popular network request library. They can work together to implement batch processing of front-end data. This article will introduce in detail how to efficiently use Vue and Axios for batch processing of data, and provide relevant code examples.

TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year Apr 17, 2024 pm 08:00 PM

According to news from this site on April 17, TrendForce recently released a report, believing that demand for Nvidia's new Blackwell platform products is bullish, and is expected to drive TSMC's total CoWoS packaging production capacity to increase by more than 150% in 2024. NVIDIA Blackwell's new platform products include B-series GPUs and GB200 accelerator cards integrating NVIDIA's own GraceArm CPU. TrendForce confirms that the supply chain is currently very optimistic about GB200. It is estimated that shipments in 2025 are expected to exceed one million units, accounting for 40-50% of Nvidia's high-end GPUs. Nvidia plans to deliver products such as GB200 and B100 in the second half of the year, but upstream wafer packaging must further adopt more complex products.

How soon will FET coins experience a second surge? How high is the forecast for the maximum increase? How soon will FET coins experience a second surge? How high is the forecast for the maximum increase? Apr 14, 2024 am 09:16 AM

As the leading currency in the field of AI artificial intelligence, FET currency has attracted much attention due to its considerable return on investment. FET currency is not only a quantitative divisible token used by the Fetch.ai platform, but also the platform’s smart contracts and oracles. An important part of. With the arrival of the bull market, the price of FET coins continues to rise, but investors are still not satisfied with this market trend. They want to know how soon will FET coins experience a second surge? I would also like to know how much the currency circle analysts predict the maximum rise of FET coins? According to the predictions of analysts in the circle, the second surge will occur in 2025, with a maximum rise of $8.15. Next, the editor will tell you in detail. How soon will FET coins experience a second surge? According to the predictions of analysts in the circle, FET currency will explode for the second time.

Vue and Axios implement synchronous processing of asynchronous data requests Vue and Axios implement synchronous processing of asynchronous data requests Jul 17, 2023 am 10:13 AM

Vue and Axios implement synchronous processing of asynchronous data requests Introduction: In modern front-end development, because the page needs to obtain data through asynchronous data requests and dynamically display it, asynchronous processing has become an inevitable requirement. However, asynchronous data requests often cause code logic to become complex and difficult to maintain. In the Vue framework, the Axios library can be used to easily implement synchronous processing of asynchronous data requests, thereby improving the readability and maintainability of the code. 1. Introduction to Vue Vue is a lightweight front-end framework.

AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix Jul 18, 2024 am 02:04 AM

This website reported on July 9 that the AMD Zen5 architecture "Strix" series processors will have two packaging solutions. The smaller StrixPoint will use the FP8 package, while the StrixHalo will use the FP11 package. Source: videocardz source @Olrak29_ The latest revelation is that StrixHalo’s FP11 package size is 37.5mm*45mm (1687 square millimeters), which is the same as the LGA-1700 package size of Intel’s AlderLake and RaptorLake CPUs. AMD’s latest Phoenix APU uses an FP8 packaging solution with a size of 25*40mm, which means that StrixHalo’s F

How do C++ functions improve the efficiency of GUI development by encapsulating code? How do C++ functions improve the efficiency of GUI development by encapsulating code? Apr 25, 2024 pm 12:27 PM

By encapsulating code, C++ functions can improve GUI development efficiency: Code encapsulation: Functions group code into independent units, making the code easier to understand and maintain. Reusability: Functions create common functionality that can be reused across applications, reducing duplication and errors. Concise code: Encapsulated code makes the main logic concise and easy to read and debug.

Vue and Axios implement error handling and prompt mechanism for data requests Vue and Axios implement error handling and prompt mechanism for data requests Jul 17, 2023 am 09:04 AM

Vue and Axios implement error handling and prompt mechanism for data requests Introduction: In Vue development, Axios is often used for data requests. However, in the actual development process, we often encounter request errors or the server returns error codes. In order to improve the user experience and detect and handle request errors in a timely manner, we need to use some mechanisms for error handling and prompts. This article will introduce how to use Vue and Axios to implement error handling and prompt mechanisms for data requests, and provide code examples. Install Axi

See all articles