• Vue3最佳实践 第六章 Pinia,Vuex与axios,VueUse 4(axios)


    Axios

      axios 是一个基于 Promise 的 HTTP 客户端,不仅可以与 vue.js 一起使用,还可以与其他前端框架以及后端 Node.js 一起使用。当你想从包括后端服务器在内的外部服务获取数据时,可以使用axios 中的方法很方便的获得数据内容。在本文档中,我们将介绍如何在 vue.js 版本 3 的环境中使用 axios。对于 Vue 3,它不仅解释了如何将它与 Options API 一起使用,还解释了如何将它与 Composition API 一起使用。
    官方文件地址https://axios-http.com/docs/intro

    第一章 Vue3项目创建 1 Vue CLI 创建vue项目
    第一章 Vue3项目创建 2 使用 Webpack 5 搭建 vue项目
    第一章 Vue3项目创建 3 Vite 创建 vue项目
    第二章 Vue3 基础语法指令
    第三章 Vue Router路由器的使用
    第四章 VUE常用 UI 库 1 ( element-plus,Ant ,naiveui,ArcoDesign)
    第四章 VUE常用 UI 库 2 ( ailwind 后台框架)
    第五章 Vue 组件应用 1( Props )
    第五章 Vue 组件应用 2 ( Emit )
    第五章 Vue 组件应用 3( Slots )
    第五章 Vue 组件应用 4 ( provide 和 inject )
    第五章 Vue 组件应用 5 (Vue 插件)
    第六章 Pinia,Vuex与axios,VueUse 1(Pinia)
    第六章 Pinia,Vuex与axios,VueUse 2(Vuex)
    第六章 Pinia,Vuex与axios,VueUse 3(VueUse)
    第六章 Pinia,Vuex与axios,VueUse 4(axios)
    第七章 TypeScript 上
    第七章 TypeScript 中
    第七章 TypeScript 下 创建Trello 任务管理器
    第八章 ESLint 与 测试 ( ESLint )
    第八章 ESLint 与 测试 ( Jest )
    第八章 ESLint 与 测试 (TypeScript 中Jest与检测环境集成)

    1 axios 设置

      我们的目标是学习如何将 axios 与 vue.js 一起使用,使用 cdn模式是最快和最简单的方法。在原生的HTML中使用axios 的方法获得数据。在浏览器访问它并显示一个远程访问获得数据列表内容。如果你不知道 axios 是什么,不用担心,我们会慢慢解释的。

    DOCTYPE html>
    <html lang="ja">
    <head>
        <meta charset="UTF-8">
        <title>学习在vue中使用axiostitle>
    head>
    <body>
        <div id="app">
            <h1>{{ message }}h1>
        div>
        <script src="https://unpkg.com/vue@3">script>
        <script src="https://unpkg.com/axios/dist/axios.min.js">script>
        <script>
        Vue.createApp({
            el: '#app',
            data(){
                return {
                    message: 'Hello Axios',
                }
            },
            mounted(){
                axios.get('https://jsonplaceholder.typicode.com/users')
                    .then(response => console.log(response))
                    .catch(error => console.log(error))
            }
    }).mount('#app')
        script>
    body>
    html>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    在 node项目中导入axios组件。

    $ npm install axios
    
    • 1

    在vue3 中使用axios获得数据的例子。

    <script setup>
    import { onMounted } from 'vue';
    import axios from 'axios'
    onMounted(() => {
          axios
            .get('https://jsonplaceholder.typicode.com/users')
            .then((response) => console.log(response))
            .catch((error) => console.log(error));
    });
    script>
    <template>
    <div >
      <div>业务内容一览div>
    template>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    2 axios方法

      axios处理方法分为同步处理与异步处理两种,axios默认的是异步处理方法。获得的数据结果在下面几个方法中进行处理。

    axios.get('/user?ID=12345')
      .then(function (response) {
     // 描述axios处理成功后要处理什么
        console.log(response);
      })
      .catch(function (error) {
     // 描述axios处理出错时要做什么
        console.log(error);
      })
      .finally(function () {
     // 无论axios的处理结果如何,都会执行
      });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    在 Vue 实例中使用 axios 中get,post ,delete,put方法创建数据远程连接。

    axios.get(url[, config])
    axios.post(url[, data[, config]])
    axios.delete(url[, config])
    axios.head(url[, config])
    axios.put(url[, data[, config]])
    axios.patch(url[, data[, config]])
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

      返回json对象在 response.data 的属性中获得数据内容, response 包含的其他内容不仅是数据,还有status、headers、statusText、config。如果只关注状态,可以看到如果使用 GET 方法处理成功则返回状态码 200,使用 POST 方法返回状态码 201。

    axios.get('https://jsonplaceholder.typicode.com/users')
          .then(response => {
            console.log(response.data)//数据内容
            console.log(response.status)
            console.log(response.headers)
            console.log(response.statusText)
            console.log(response.config)
          })
          .catch(error => console.log(error))
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    1 axios 异步方法

    通过异步方法获得数据列表,在将列表中的数据内容显示到模板v-for指令中。

    <script setup>
    import {ref,onMounted  } from 'vue';
    import axios from 'axios'
    const userlist=ref([]);
    onMounted(() => {
          axios
            .get('https://jsonplaceholder.typicode.com/users')
            .then((response) => userlist.value=response.data)
            .catch((error) => console.log(error));
        });
    script>
    <template>
    <div class="m-4 p-4" style="height:97vh;overflow-y:auto">
      <div>业务内容一览div>
      <div v-for="list in userlist ">
        id:{{list.id}} name:{{list.name}}
      div>
     div>
    template>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    2 axios 同步方法

      Composition API 中使用了 async 和 await 设置的函数为同步函数。很多业务都需要axios 同步方法来处理,我们将axios处理函数设置关键字async 和 await,这个函数就是同步函数。

    同步处理关键字 async , await

    <script setup>
    import {ref,onMounted  } from 'vue';
    import axios from 'axios'
    const userlist=ref([]);
        // 使用 async 和 await 函数定义同步关键字
        onMounted(async () => {
          try {
            const response = await axios.get(
              'https://jsonplaceholder.typicode.com/users'
            );
            userlist.value=response.data
          } catch (error) {
            console.log(error);
          }
        });   
    script>
    <template>
    <div class="m-4 p-4" style="height:97vh;overflow-y:auto">
      <div>业务内容一览div>
          <div v-for="list in userlist ">
            id:{{list.id}} name:{{list.name}}
          div>
      div>
    template>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

      普通方法设置成同步方法。

    <script setup>
    import {ref,onMounted  } from 'vue';
    import axios from 'axios'
    const userlist=ref([]);
        onMounted( () => {
          init();
        });   
        //定义同步方法
        const init =async () => {
          try {
            const response = await axios.get(
              'https://jsonplaceholder.typicode.com/users'
            );
            userlist.value=response.data
          } catch (error) {
            console.log(error);
          }
        }
    script>
    <template>
    <div class="m-4 p-4" style="height:97vh;overflow-y:auto">
      <div>业务内容一览div>
          <div v-for="list in userlist ">
            id:{{list.id}} name:{{list.name}}
          div>
      div>
    template>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    在这里插入图片描述

    3 创建实例与配置拦截器

    ​  您可以使用 create 方法创建一个 axios 实例。可以在 create 方法的参数中设置 baseURL,headers表头信息等其他url请求设置。axios 实例

    <script setup>
    import {ref,onMounted} from 'vue';
    import axios from 'axios'
    const userlist=ref([]);
        onMounted( () => {
          init();
        });  
    const headers = {
       Authorization: `Bearer`
    }     
        const init =async () => {
          const instance = axios.create({
            baseURL:'https://jsonplaceholder.typicode.com/users',
            headers: headers
          });
            const response = await instance.get();
            userlist.value=response.data
        }
    script>
    <template>
    <div class="m-4 p-4" style="height:97vh;overflow-y:auto">
      <div>业务内容一览div>
      <div v-for="list in userlist ">
        id:{{list.id}} name:{{list.name}}
      div>
      div>
    template>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    配置拦截器

      拦截器可以在 axios 发送请求之前或从服务器返回响应时对 Request 和 Response 对象进行业务处理的监听方法。

    axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com';
    axios.interceptors.request.use((config) => {
      console.log(config)
      return config;
    });
    //在拦截器中设置 baseURL
    axios.interceptors.request.use((config) => {
     config.baseURL = 'https://test.com';
      console.log(config)
      return config;
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    在浏览器中可以看到 baseURL 已被覆盖。显示错误消息,因为无法访问 https://test.com这个url地址。

    axios.interceptors.response.use((response) => {
      console.log(response);
      return response;
    });
    
    • 1
    • 2
    • 3
    • 4

      Response 可用于在认证失败并返回状态码401(Unauthorized)时候,作认证失败时的注销处理。通过检查每个响应的状态码,可以根据每个代码进行不同的业务处理。

    axios.interceptors.response.use(
      (response) => response,
      (error) => {
        if (error.response.status === 401) {
          //logout 注销处理
        }
        return Promise.reject(error);
      }
    );
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    4 axios 插件plugins

      创建一个 axios.js 文件,在文件中定义一个axios插件plugins功能。插件中允许我们设置一个共通的 baseURL方法路径,项目中使用axios方法可以直接引用到这个公共url路径。

    axios.js

    import axios from 'axios';
    const axiosPlugin = {
      install(app, options) {
        const axiosInstance = axios.create({
          baseURL: options.baseURL,
        });
        app.provide('axios', axiosInstance);
      },
    };
    export default axiosPlugin;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    main.js

    项目中vue组件引入axiosPlugin插件功能,插件中引入一个共通的baseURL: 'https://jsonplaceholder.typicode.com/'访问路径。

    import { createApp } from 'vue'
    import router from './router'
    import App from './App.vue'
    import axiosPlugin from './axios';
    const app = createApp(App)
    app.use(router)
    app.use(axiosPlugin, {
        //所有axios访问路径头
        baseURL: 'https://jsonplaceholder.typicode.com/'
     });
    app.mount('#app')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    axios使用

      在vue组件中获得inject 过滤方法,设置每个axios对象访问url的时候都要通过inject方法过滤访问的url地址。所有的地址baseURL+ 后台系统的业务路径

    <script setup>
    import {ref,onMounted  } from 'vue';
    import { inject } from 'vue';
    const axios = inject('axios');
    const userlist=ref([]);
    onMounted( () => {
      init();
    }); 
    const init=async ()=>{
       //访问地址是 'https://jsonplaceholder.typicode.com/'+ '/users'
      const response = await axios.get('/users');
      console.log(response.data);
      userlist.value=response.data;
    
    }
    script>
    <template>
    <div class="m-4 p-4" style="height:97vh;overflow-y:auto">
      <div>业务内容一览div>
      <div v-for="list in userlist ">
        id:{{list.id}} name:{{list.name}}
      div>
     div>
    template>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
  • 相关阅读:
    解决方案-权限系统设计
    HDU 1213 - How Many Tables(并查集 or dfs)
    暖通空调系统使用Modbus转Profinet网关应用配置案例
    第十四届蓝桥杯大赛软件赛决赛 C/C++ 大学 B 组 试题 C: 班级活动
    antd+react Hook弹窗改进版
    endpoint=DefaultEndpoint{ serviceUrl=‘http://127.0.0.1:10086/eureka/
    express multiparty minio实现图片的上传
    .Net 一套接口多实现
    Oracle开启Supplemental Logging补充日志
    误删docker容器(container)后的恢复
  • 原文地址:https://blog.csdn.net/zhtbs/article/details/133139367