Vue二次封装axios流程详解

 更新时间:2022年10月27日 15:20:09   作者:小白探索世界欧耶!~  
在vue项目中,和后台交互获取数据这块,我们通常使用的是axios库,它是基于promise的http库,下面这篇文章主要给大家介绍了关于Vue3引入axios封装接口的两种方法,需要的朋友可以参考下

一、为什么要封装axios

api统一管理,不管接口有多少,所有的接口都可以非常清晰,容易维护。

通常我们的项目会越做越大,页面也会越来越多,如果页面非常的少,直接用axios也没有什么大的影响,那页面组件多了起来,上百个接口呢,这个时候后端改了接口,多加了一个参数什么的呢?那就只有找到那个页面,进去修改,整个过程很繁琐,不易于项目的维护和迭代。

这个时候如果我们统一的区管理接口,需要修改某一个接口的时候直接在api里修改对应的请求,是不是很方便呢?因为我们用的最多的还是get post请求,我们就可以针对封装。

二、怎么封装axios

1. 拿到项目和后端接口,首先要配置全局代理;

2. 接着全局封装axios和request.js;

3. 过滤axios请求方式,控制路径,参数的格式,http.js;

4. 正式封装api.js;

5. 页面调用;

三、具体步骤

vue项目的前期配置

1. 终端输入

npm i axios -S

2. 在项目中 main.js 文件中输入

import axios from "axios";

配置config文件中的代理地址

修改项目中config目录下的index.js文件。【也可能是vue.config.js 文件】

'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
  dev: {
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        pathRewrite: {
          '^/': ''
        }
      },
      '/ws/*': {
        target: 'ws://127.0.0.1:8080',
        ws: true
      }
    },
    // Various Dev Server settings
    host: 'localhost', // can be overwritten by process.env.HOST
    port: 8082, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: false,
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
    // Use Eslint Loader?
    // If true, your code will be linted during bundling and
    // linting errors and warnings will be shown in the console.
    useEslint: true,
    // If true, eslint errors and warnings will also be shown in the error overlay
    // in the browser.
    showEslintErrorsInOverlay: false,
    /**
     * Source Maps
     */
    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-module-eval-source-map',
    // If you have problems debugging vue-files in devtools,
    // set this to false - it *may* help
    // https://vue-loader.vuejs.org/en/options.html#cachebusting
    cacheBusting: true,
    cssSourceMap: true
  },
  build: {
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'),
    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    /**
     * Source Maps
     */
    productionSourceMap: true,
    // https://webpack.js.org/configuration/devtool/#production
    devtool: '#source-map',
    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],
    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  }
}

封装axios实例-request.js

/****   request.js   ****/
// 导入axios
import axios from 'axios'
// 使用element-ui Message做消息提醒
import { Message} from 'element-ui';
//1. 创建新的axios实例,
const service = axios.create({
  // 公共接口--这里注意后面会讲
  baseURL: process.env.BASE_API,
  // 超时时间 单位是ms,这里设置了3s的超时时间
  timeout: 3 * 1000
})
// 2.请求拦截器
service.interceptors.request.use(config => {
  //发请求前做的一些处理,数据转化,配置请求头,设置token,设置loading等,根据需求去添加
  config.data = JSON.stringify(config.data); //数据转化,也可以使用qs转换
  config.headers = {
    'Content-Type':'application/json' //配置请求头
  }
  //如有需要:注意使用token的时候需要引入cookie方法或者用本地localStorage等方法,推荐js-cookie
  //const token = getCookie('名称');//这里取token之前,你肯定需要先拿到token,存一下
  //if(token){
  //config.params = {'token':token} //如果要求携带在参数中
  //config.headers.token= token; //如果要求携带在请求头中
  //}
  return config
}, error => {
  Promise.reject(error)
})
// 3.响应拦截器
service.interceptors.response.use(response => {
  //接收到响应数据并成功后的一些共有的处理,关闭loading等
  return response
}, error => {
  /***** 接收到异常响应的处理开始 *****/
  if (error && error.response) {
    // 1.公共错误处理
    // 2.根据响应码具体处理
    switch (error.response.status) {
      case 400:
        error.message = '错误请求'
        break;
      case 401:
        error.message = '未授权,请重新登录'
        break;
      case 403:
        error.message = '拒绝访问'
        break;
      case 404:
        error.message = '请求错误,未找到该资源'
        window.location.href = "/NotFound"
        break;
      case 405:
        error.message = '请求方法未允许'
        break;
      case 408:
        error.message = '请求超时'
        break;
      case 500:
        error.message = '服务器端出错'
        break;
      case 501:
        error.message = '网络未实现'
        break;
      case 502:
        error.message = '网络错误'
        break;
      case 503:
        error.message = '服务不可用'
        break;
      case 504:
        error.message = '网络超时'
        break;
      case 505:
        error.message = 'http版本不支持该请求'
        break;
      default:
        error.message = `连接错误${error.response.status}`
    }
  } else {
    // 超时处理
    if (JSON.stringify(error).includes('timeout')) {
      Message.error('服务器响应超时,请刷新当前页')
    }
    error.message = '连接服务器失败'
  }
  Message.error(error.message)
  /***** 处理结束 *****/
  //如果不需要错误处理,以上的处理过程都可省略
  return Promise.resolve(error.response)
})
//4.导入文件
export default service

四、封装请求-http.js

/****   http.js   ****/
// 导入封装好的axios实例
import request from './request'
const http ={
  /**
   * methods: 请求
   * @param url 请求地址
   * @param params 请求参数
   */
  get(url,params){
    const config = {
      method: 'get',
      url:url
    }
    if(params) config.params = params
    return request(config)
  },
  post(url,params){
    const config = {
      method: 'post',
      url:url
    }
    if(params) config.data = params
    return request(config)
  },
  put(url,params){
    const config = {
      method: 'put',
      url:url
    }
    if(params) config.params = params
    return request(config)
  },
  delete(url,params){
    const config = {
      method: 'delete',
      url:url
    }
    if(params) config.params = params
    return request(config)
  }
}
//导出
export default http

五、正式封装API用于发送请求-api.js

import request from "@/utils/request.js";
import qs from "qs";
const baseUrl = '/api/jwt/auth'
//登录
export function authCodeLogin(params) {
  return request({
    url: baseUrl + "/authCodeLogin/" + params.code,
    method: "get",
  });
}
//退出
export function authLogout(params) {
  return request({
    url: baseUrl + "/logout",
    method: "get",
  });
}
//获取用户数据
export function getUserInfo(params) {
  return request({
    url: baseUrl + "/getUserInfo",
    method: "get",
    params:qs.stringfy(params)
  });
}
//其实,也不一定就是params,也可以是 query 还有 data 的呀!
//params是添加到url的请求字符串中的,用于get请求。会将参数加到 url后面。所以,传递的都是字符串。无法传递参数中含有json格式的数据
//而data是添加到请求体(body)中的, 用于post请求。添加到请求体(body)中,json 格式也是可以的。

六、如何在vue文件中调用

用到哪个api 就调用哪个接口

import { authCodeLogin  } from '@/api/api.js'
   getModellogin(code){
      let params = {
        code: code,
      }
      authCodeLogin(params).then(res=>{
        if (res.code === 200) {
          localStorage.clear()
          // 菜单
          this.$store.dispatch('saveMenu', [])
          // this.getFloorMenu()
          // this.getmenu()
          this.$router.push('/')
        }else{
          console.log('error');
        }
      })
    },

到此这篇关于Vue二次封装axios流程详解的文章就介绍到这了,更多相关Vue封装axios内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • vue利用openlayers加载天地图和高德地图

    vue利用openlayers加载天地图和高德地图

    这篇文章主要介绍了 vue利用openlayers加载天地图和高德地图,下文章主要由两部分完成openlayers加载天地图和加载高德地图,下面来看看详细内容吧,需要的朋友可以参考一下,希望对大家有所帮助
    2021-11-11
  • vue iview实现动态路由和权限验证功能

    vue iview实现动态路由和权限验证功能

    这篇文章主要介绍了vue iview实现动态路由和权限验证功能,动态路由控制分为两种:一种是将所有路由数据存储在本地文件中,另一种则是本地只存储基本路由,具体内容详情大家参考下此文
    2018-04-04
  •  用Vue Demi 构建同时兼容Vue2与Vue3组件库

     用Vue Demi 构建同时兼容Vue2与Vue3组件库

    这篇文章主要介绍了 用Vue Demi 构建同时兼容Vue2与Vue3组件库,我们通过考虑其功能、工作原理以及如何开始使用它来了解 Vue Demi,下面我们一起进入文章学起来吧
    2022-02-02
  • Vue.js 2.x之组件的定义和注册图文详解

    Vue.js 2.x之组件的定义和注册图文详解

    组件Component是 Vue.js 最强大的功能之一。组件可以扩展 HTML 元素,封装可重用的代码,这篇文章主要介绍了Vue.js 2.x:组件的定义和注册,需要的朋友可以参考下
    2018-06-06
  • 使用vue.js实现联动效果的示例代码

    使用vue.js实现联动效果的示例代码

    本篇文章主要介绍了使用vue.js实现联动效果的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-01-01
  • 详解Vue.js动态绑定class

    详解Vue.js动态绑定class

    Vue.js的核心是一个响应的数据绑定系统,它允许我们在普通 HTML 模板中使用特殊的语法将 DOM “绑定”到底层数据。被绑定的DOM 将与数据保持同步,每当数据有改动,相应的DOM视图也会更新。基于这种特性,通过vue.js动态绑定class就变得非常简单。一起来看下吧
    2016-12-12
  • vue中element 的upload组件发送请求给后端操作

    vue中element 的upload组件发送请求给后端操作

    这篇文章主要介绍了vue中element 的upload组件发送请求给后端操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-09-09
  • Vue实现简易计算器

    Vue实现简易计算器

    这篇文章主要为大家详细介绍了用Vue制作的简易计算器,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-02-02
  • Vue 进入/离开动画效果

    Vue 进入/离开动画效果

    这篇文章主要介绍了Vue 进入/离开动画效果,代码简单易懂,非常不错,具有参考借鉴价值,需要的朋友可以参考下
    2017-12-12
  • Vue组件之全局组件与局部组件的使用详解

    Vue组件之全局组件与局部组件的使用详解

    本篇文章主要介绍了Vue组件之全局组件与局部组件的使用详解,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-10-10

最新评论