当前位置:   article > 正文

13 在Vue3中使用axios异步加载数据_vue3 和 await axios.get 列表数据

vue3 和 await axios.get 列表数据

概述

Asynchronous functions in JavaScript are defined by the async syntax and return a Promise. These functions operate asynchronously via the Event loop, using an implicit promise, which is an object that may return a result in the future.

JavaScript 中的异步函数由 async 语法定义,并返回一个 Promise。这些函数通过事件循环进行异步操作,使用隐式 Promise,即可能在未来返回结果的对象。

As part of the JavaScript language, you can declare asynchronous blocks of code inside a Vue component’s method by including the async keyword in front of a method.

作为 JavaScript 语言的一部分,您可以通过在方法前添加 async 关键字,在 Vue 组件的方法中声明异步代码块。

You can use Promise chaining methods, such as the then() and catch() functions or try the await syntax of ES6 inside these Vue methods and return the results accordingly.

您可以使用 Promise 连锁方法,如 then() 和 catch() 函数,或在这些 Vue 方法中尝试使用 ES6 的 await 语法,并返回相应的结果。

Here is an example using the built-in fetch API to fetch data inside a component method as an asynchronous function with async/await keywords:

下面是一个示例,使用内置的获取 API,以异步函数的形式在组件方法内获取数据,并使用 async/await 关键字:

<script>
export default {
  methods: {
    async getAdvice() {
      const response = await fetch('https://api.adviceslip.com/advice')
      return response;
    },
  },
}
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

Axios is a popular JavaScript library that allows you to make external requests for data using Node.js. It has wide browser support making it a versatile library when making HTTP or API requests. We will be using this library in the next exercise.

Axios 是一个流行的 JavaScript 库,可让您使用 Node.js 从外部请求数据。它支持多种浏览器,因此是进行 HTTP 或 API 请求的通用库。我们将在下一个练习中使用该库。

练习:使用axios请求数据

In this exercise, you will asynchronously fetch data from an external API source and display it on the frontend using computed props.

在本练习中,您将异步从外部 API 源获取数据,并使用计算道具将其显示在前端。

Let’s create a new Vue component called Exercise2-05 by adding the Exercise2-05.vue file to the ./src/components/ folder.

让我们在 ./src/components/ 文件夹中添加 Exercise2-05.vue 文件,创建一个名为 Exercise2-05 的新 Vue 组件。

在App.vue中,引入并使用该组件:

<script setup>
import Exercise from "./components/Exercise2-05.vue";
</script>
<template>
  <Exercise/>
</template>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

安装axios依赖:

yarn add axios

# 或者
npm add axios
  • 1
  • 2
  • 3
  • 4

In Exercise2-05.vue, let’s start by importing axios into our component and creating a method called fetchAdvice(). We use axios to call a response from https://api.adviceslip.com/advice and then console.log the result. Also, let’s include a button that has a click event bound to the fetchAdvice() call:

在 Exercise2-05.vue 中,我们首先将 axios 导入组件,然后创建一个名为 fetchAdvice() 的方法。我们使用 axios 从 https://api.adviceslip.com/advice 调用响应,然后在 console.log 中记录结果。此外,让我们加入一个按钮,该按钮的点击事件绑定到 fetchAdvice() 调用:

<template>
  <div class="container">
    <h1>Async fetch</h1>
    <button @click="fetchAdvice()">Learn something
      profound
    </button>
  </div>
</template>
<script>
import axios from 'axios'

export default {
  methods: {
    async fetchAdvice() {
      return axios.get
      ('https://api.adviceslip.com/advice').then((response) => {
        console.log(response)
      })
    },
  },
}
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

We are only interested in the data object inside the response object. Assign this data object to a Vue data prop called response, which we can reuse:

我们只对响应对象中的数据对象感兴趣。将该数据对象分配给一个名为 response 的 Vue 数据道具,我们可以重复使用该道具:

<script>
import axios from 'axios'

export default {
  data() {
    return {
      axiosResponse: {},
    }
  },
  methods: {
    async fetchAdvice() {
      return axios.get
      ('https://api.adviceslip.com/advice').
      then(response => {
        this.axiosResponse = response.data
      })
    },
  },
}
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

Output quote from inside the response prop object using a computed prop that will update every time the response prop changes. Use a ternary operator to perform a conditional statement to check whether the response prop contains the slip object to avoid errors:

使用一个计算道具从响应道具对象内部输出引用,每次响应道具发生变化时,该道具都会更新。使用三元操作符执行条件语句,检查响应道具是否包含滑点对象,以避免出错:

<template>
  <div class="container">
    <h1>Async fetch</h1>
    <button @click="fetchAdvice()">Learn something
      profound</button>
    <blockquote v-if="quote">{{ quote }}</blockquote>
  </div>
</template>
<script>
import axios from 'axios'
export default {
  data() {
    return {
      axiosResponse: {},
    }
  },
  computed: {
    quote() {
      return this.axiosResponse &&
      this.axiosResponse.slip
          ? this.axiosResponse.slip.advice
          : null
    },
  },
  methods: {
    async fetchAdvice() {
      return axios.get
      ('https://api.adviceslip.com/advice').
      then(response => {
        this.axiosResponse = response.data
      })
    },
  },
}
</script>
  • 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
  • 31
  • 32
  • 33
  • 34
  • 35

As a final touch, include a loading data prop so the user can see when the UI is loading. Set loading to false by default. Inside the fetchAdvice method, set loading to true.

最后,加入一个加载数据道具,这样用户就能看到用户界面何时加载。默认将加载设置为 false。在 fetchAdvice 方法中,将加载设置为 true。

When the GET request completes (resolve/reject), within the finally() chain, set it back to false after 4 seconds using the setTimeout function. You can use a ternary operator to change the button text between the loading state and its default state:

当 GET 请求完成后(解析/拒绝),在 finally() 链中使用 setTimeout 函数在 4 秒后将其设置为 false。您可以使用三元运算符在加载状态和默认状态之间更改按钮文本:

<template>
  <div class="container">
    <h1>Async fetch</h1>
    <button @click="fetchAdvice()">{{ loading ? 'Loading...' : 'Learn something profound' }}</button>
    <blockquote v-if="quote">{{ quote }}</blockquote>
  </div>
</template>
<script>
import axios from 'axios'
export default {
  data() {
    return {
      loading: false,
      axiosResponse: {},
    }
  },
  computed: {
    quote() {
      return this.axiosResponse &&
      this.axiosResponse.slip
          ? this.axiosResponse.slip.advice
          : null
    },
  },
  methods: {
    async fetchAdvice() {
      this.loading = true
      try {
        const response = await axios.get("https://api.adviceslip.com/advice");
        this.axiosResponse = response.data;
      } catch (error) {
        console.log(error);
      } finally {
        setTimeout(() => {
          this.loading = false;
        }, 4000);
      }
    },
  },
}
</script>
  • 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
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

In this exercise, we saw how we can fetch data from an external source, assign it to a computed prop, display it in our template, and apply a loading state to our content.

在本练习中,我们看到了如何从外部源获取数据、将其分配给计算道具、将其显示在模板中并为内容应用加载状态。

At this point, we have explored the different approaches to working with the local data of a Vue component.

至此,我们已经探索了处理 Vue 组件本地数据的不同方法。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/639143
推荐阅读
相关标签
  

闽ICP备14008679号