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

php中世界最好的语言
Release: 2018-05-28 15:01:36
Original
3252 people have browsed it

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!

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