如何在 Vue 中使用 Axios 实现异步请求

2023-05-19 08:35:48

如何在 Vue 中使用 Axios 实现异步请求

import axios from 'axios'

export default {
  data() {
    return {
      posts: [],
      loading: false,
      error: null
    }
  },
  methods: {
    async fetchPosts() {
      try {
        this.loading = true
        const response = await axios.get('https://jsonplaceholder.typicode.com/posts')
        this.posts = response.data
      } catch (error) {
        this.error = error.message
      } finally {
        this.loading = false
      }
    }
  },
  mounted() {
    this.fetchPosts()
  }
}

上述代码中,我们使用了 Vue 中的 Axios 库来处理异步请求。在创建 Vue 实例时,首先引入 Axios 库,然后定义了一个 data 属性,该属性包含了应用程序需要用到的数据。为了请求数据,我们创建了一个名为 fetchPosts 的方法,在这个方法中,我们使用 async/await 来处理异步请求,使代码看起来更加清晰易懂。在捕获错误和完成请求后,我们使用 loading 状态和 error 状态来处理 UI 层面的操作。最后,在执行 mounted 钩子时,我们调用 fetchPosts 方法来获取数据。

  • 作者:
  • 原文链接:
    更新时间:2023-05-19 08:35:48