Vue——axios的二次封装

一、请求和传递参数

在 Vue 中,发送请求一般在 created 钩子中,当然放在 mounted 钩子中也没问题。

以下请求的前提都是安装了 axios,并且 import axios from ‘axios’ 成功导入

1、get 请求

get 请求传参,在地址里面通过 ?xxx=123 的形式

// Vue 环境中
 async created() {
   let res = await axios.get(
     "http://testapi.xuexiluxian.cn/api/slider/getSliders?xxx=123"
   );
   console.log(res);
 }
2、post 请求

post 请求传参,在第二个参数里面传递

// Vue 环境中
 async created() {
   let res = await axios.post('http://testapi.xuexiluxian.cn/api/course/mostNew', {
     pageNum: 1,
     pageSize: 5
   })
   console.log(res);
 }

![在这里插入图片描述](https://img-blog.csdnimg.cn/533bb74a2e7844cf8c13b6a1f9e41041.png

3、axios 请求配置

请求配置里面可以设置很多属性

  // Vue环境中
  async created() {
    let res = await axios({
      url: 'http://testapi.xuexiluxian.cn/api/course/mostNew',
      method: 'post', // 默认是 get 请求
      headers: {}, // 自定义请求头
      data: {  // post 请求,前端给后端传递的参数
        pageNum: 1,
        pageSize: 5
      }, 
      params: {}, // get 请求,前端给后端传递的参数
      timeout: 0, // 请求超时
      responseType: 'json' // 返回的数据类型
    })
  console.log(res);
  }

在这里插入图片描述

二、axios 的二次封装

目的:方便统一管理

注意:先安装 axios 才可以使用,终端键入:npm i axios,之后回车安装它

1、配置拦截器

在 src 目录下新建 utils 文件夹,该文件夹下创建 request.js 文件

request.js 文件

首先创建 axios 对象
添加请求拦截器(前端给后端的参数)
添加响应拦截器(后端给前端的数据)

import axios from 'axios'

// 创建 axios 对象
const instance = axios.create({
    baseURL: 'http://testapi.xuexiluxian.cn/api', // 根路径
    timeout: 2000 // 网络延时
})

// 添加请求拦截器 => 前端给后端的参数【还没到后端响应】
instance.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器 => 后端给前端的数据【后端返回给前端的东西】
instance.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});

// 最终返回的对象
export default instance
2、发送请求

在需要发请求的组件中,导入 request.js, 之后发送请求即可

App.vue 组件

在需要使用的组件中 导入 request
直接发送请求即可

<template>
  <div id="app">前端杂货铺</div>
</template>

<script>
import request from "./utils/request";
export default {
  name: "App",
  data() {
    return {};
  },
  created() {
  	// get 请求
    request({
      url: "/course/category/getSecondCategorys",
    }).then((res) => {
      console.log(res);
    });

	// post 请求
    request({
      url: "/course/mostNew",
      method: "post",
      data: {
        pageNum: 1,
        pageSize: 5,
      },
    }).then((res) => {
      console.log(res);
    });
  }
}
</script>

在这里插入图片描述

三、API 的解耦

API 解耦的目的:

为了同一个接口可以多次使用
为了方便 api 请求统一管理

1、配置文件对应的请求

在 src 目录下新建 api 文件夹,该文件夹下创建 xxx.js 文件,配置对应请求

./api/course.js 文件

发送与课程相关的请求

import request from "../utils/request";

// 获取一级分类(get请求)
export function getSendCategorys() {
    return request({
        url: '/course/category/getSecondCategorys',
    })
}

// 查询课程(post请求)
export function courseSearch(data) {
    return request({
        url: '/course/search',
        method: 'post',
        data
    })
}
2、获取请求的数据

App.vue 组件

从文件定义的请求中导入对应函数
获取数据

<template>
  <div id="app"></div>
</template>

<script>
import { getSendCategorys, courseSearch } from "./api/course";
export default {
  name: "App",
  data() {
    return {};
  },
  created() {
  	// 获取一级分类
    getSendCategorys().then((res) => {
      console.log(res);
    });
    // 查询课程(有参数的传递)
    courseSearch({
      pageNum: 1,
      pageSize: 5
    }).then((res) => {
      console.log(res);
    });
  }
}

在这里插入图片描述
在这里插入图片描述

四、总结

对 axios 的二次封装,在企业级项目中是 必须 要配置的。

因为经过封装的 axios,更容易使用和管理,并且可以 减少代码量,让 逻辑更清晰

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值