Vue——axios的二次封装


一、请求和传递参数

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

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

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);
  }

在这里插入图片描述

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,更容易使用和管理,并且可以 减少代码量,让 逻辑更清晰

这里是 前端杂货铺,期待您的 三连 + 关注

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>